basic basic - 1 month ago 27
Android Question

Remove multiple items from ExpandableListView

I have an ExpandableListView and a checkbox to remove items depending on a users preference. It "technically" works but the issue I am having is I have to click the checkbox 4 or 5 times to actually remove all of the needed entries.

Any ideas what I am missing?

chkOnline.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
for(int i = 0; i < devices.size(); i++){
if(!devices.get(i).isOnline()){
devices.remove(i);
}
}
adapter.notifyDataSetChanged();
}
}
});

Answer

The problem here is that you are changing the size of the list while removing its items:

Suppose your list had a size of 3:

//first iteration
i = 0, limit = 2 (i < size())
l = [1,2,3]
1 is online => l = [1,2]

//second iteration
i = 1, limit = 1 (because size() now returns 2 and i < size())
l = [2,3]

And the loop ends without checking the last element (3) on the original list.

To fix this you can simply iterate from end to start:

for(int i = devices.size() - 1; i >= 0; i--){
    if(!devices.get(i).isOnline()){
        devices.remove(i);
    }
}
Comments