Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Removing item from ListView?

final String[] exampleData = new String[] {
                "How old am I?",
                "What's my middle name?",
                "What is my major?",
                "What's my girlfriend's name?",
                "Is this an example?"
        };

        final ListView questionList = (ListView) rootView.findViewById(R.id.questionList);
        final ArrayAdapter<String> questionListAdapter = new ArrayAdapter<String>(
                getActivity(),
                R.layout.item_question,
                R.id.questionText,
                exampleData
        );

        final DialogInterface.OnClickListener mDialogListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        //Todo link to question at "which"
                        Intent edit = new Intent(getActivity(), EditQuestionActivity.class);
                        startActivity(edit);
                        break;
                    case 1:
                        //Todo: delete question from quiz object
                        questionListAdapter.remove(questionListAdapter.getItem(which));
                        questionListAdapter.notifyDataSetChanged();
                        break;
                }
            }
        };

So, my object is to present an option list on LONG click, which is successful, and upon chosing the Delete option (at index 1), it should remove the item found at the long click index. But I recieve this error...

java.lang.UnsupportedOperationException

...pointint to this line...

questionListAdapter.remove(questionListAdapter.getItem(which));

Any suggestions?!

1 Answer

You use the following:

questionListAdapter.remove(questionListAdapter.getItem(which));

but note that 'which' is the value of the item clicked within the Dialog (it takes values depending on the number of list items in the Dialog).

Potential fix: Try to get the position of the list item which was long clicked and remove the element of the ArrayAdapter with that. That should do it! Let me know how it goes. :)

Oh! I see. The int which value is telling the onClick method that I clicked either the Edit or Delete options (indexes 0 and 1 of the dialog). I'll append this comment with an updated version of the code that works, once I fix it! Thanks for the help!!!

Update:

longClicker = new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position,
                                           long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setItems(R.array.question_long_click_options,
                        new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                //Todo link to question at "which"
                                Intent edit = new Intent(getActivity(), EditQuestionActivity.class);
                                startActivity(edit);
                                break;
                            case 1:
                                //Todo: delete question from quiz object
                                questionListAdapter.remove(questionListAdapter.getItem(position));
                                questionListAdapter.notifyDataSetChanged();
                                break;
                        }
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
                return true;
            }
        };

So, this is my new OnItemLongClickListener with the AlertDialog's onClick method set as an inner-method. I still get the same error pointing to the same line of code, though I've changed which to position to get the item's position in the list.

Ben Jakuben
Ben Jakuben
Treehouse Teacher

Sorry for the delay here! This is an interesting issue. You are using a static array (exampleData) as the data behind your adapter. We aren't allowed to add or remove from a static array like that. Even though the ArrayAdapter class has the methods to do so, they won't work on this type of array.

You should be able to switch exampleData to a dynamic collection, like an ArrayList. Then you'll be able to add or remove using the adapter.

final ArrayList<String> exampleData = new ArrayList<String>();
exampleData.add("How old am I?");
exampleData.add("What's my middle name?");
exampleData.add("What is my major?");
exampleData.add("What's my girlfriend's name?");
exampleData.add("Is this an example?");

Hope this helps! Let us know if you are still stuck.

It worked! Here's a snippit of the game's "QuestionListFragment" class...

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_question_list, container, false);
        mSwipeRefreshLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipeRefreshLayout);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getQuestions();
            }
        });

        questionList = (ListView) rootView.findViewById(android.R.id.list);

        Intent intent = getActivity().getIntent();
        quizId = intent.getStringExtra(ParseConstants.KEY_QUIZ_ID);
        getQuestions();

        questionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });

        questionList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position,
                                           long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setItems(R.array.question_long_click_options,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        //Todo link to question at "which"
                                        Intent edit = new Intent(getActivity(), EditQuestionActivity.class);
                                        startActivity(edit);
                                        break;
                                    case 1:
                                        //Todo: delete question from quiz object
                                        ParseObject question = mQuestions.get(position);
                                        mQuestions.remove(question);
                                        question.deleteInBackground(new DeleteCallback() {
                                            @Override
                                            public void done(ParseException e) {
                                                getQuestions();
                                            }
                                        });
                                        break;
                                }
                            }
                        });
                AlertDialog dialog = builder.create();
                dialog.show();
                return true;
            }
        });

        return rootView;
    }

    private void getQuestions() {
        ParseQuery<ParseObject> getQuiz = ParseQuery.getQuery(ParseConstants.CLASS_QUIZ);
        getQuiz.getInBackground(quizId, new GetCallback<ParseObject>() {
            @Override
            public void done(ParseObject quiz, ParseException e) {

                if (mSwipeRefreshLayout.isRefreshing()){
                    mSwipeRefreshLayout.setRefreshing(false);
                }

                if (e == null) {
                    quizQuestionCount = quiz.getInt(ParseConstants.KEY_QUIZ_QUESTION_COUNT);

                    ParseQuery<ParseObject> questionQuery = new ParseQuery<ParseObject>("Questions");
                    questionQuery.whereEqualTo("belongsToQuiz", quizId);
                    questionQuery.addAscendingOrder("createdAt");
                    questionQuery.findInBackground(new FindCallback<ParseObject>() {
                        @Override
                        public void done(List<ParseObject> questions, ParseException e) {
                            mQuestions = questions;
                            QuestionsAdapter questionsAdapter = new QuestionsAdapter(getActivity(), mQuestions);
                            setListAdapter(questionsAdapter);
                        }
                    });

                    try {
                        QuizInfoActivity.QuizInfoActivity.finish();
                    } catch (Exception error) {
                        error.getMessage();
                    }

                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getQuestions();
    }

Everything is working 100 perfect. :)