Search code examples
androidarraylistdialogandroid-dialogmultichoiceitems

Removing items from multiChoiceItems dialog interface not working


I'm trying to use a dialog that shows an ArrayList using multiChoiceItems. I want to check what items I want to remove, click a button to remove/ close the dialog and have the items be removed next time I open the dialog.

When I debug the code below, I find that I go through the loop for every item selected but none of the items are actually removed. I feel like I'm missing something probably pretty trivial here and I would love some help!

I know I have to take into account indexes changing if I remove multiple items so don't worry about that. I'll do that after I can remove a first item by itself!

Thanks a lot!

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Title");
            mSelectedItems.clear();
            builder.setMultiChoiceItems(myList,null,
                    new DialogInterface.OnMultiChoiceClickListener(){

                        @Override
                        public void onClick(DialogInterface dialog,int which, boolean isChecked){
                            if (isChecked) {
                                // If the user checked the item, add it to the selected items
                                mSelectedItems.add(which);
                            } else if (mSelectedItems.contains(which)) {
                                // Else, if the item is already in the array, remove it
                                mSelectedItems.remove(Integer.valueOf(which));
                            }

                        }
                    });

            builder.setPositiveButton("Remove from list", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    for(int i=0;i<mSelectedItems.size();i++){
                        arrayChoices.remove(mSelectedItems.get(i));
                    }
                    myList = arrayChoices.toArray(new CharSequence[arrayChoices.size()]);
                }
            });

            builder.setNegativeButton("End", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });


            builder.show();

Solution

  • Casted mSelectedItems.get(i) to int and it worked. It shows mSelectedItems.get(i) is an integer in debug though which makes me wonder why it didn't work already.