java.util.ConcurrentModificationException android after remove elements from array list

brpaz picture brpaz · Nov 23, 2012 · Viewed 19.7k times · Source

I have the folloing code in my android app:

/**
 * callback executed after fetching the data.
 */
public void OnPointsFetch(ArrayList<Shop> result) {

    toggleLoader(false);

    this.shops = result;

    if(activeFilter == Constants.POINTS_FILTER_AVAILABLE){
        for(Shop s : result){
            if(s.getClientPoints().getPointsAvailable() == 0){
                this.shops.remove(s);
            }
        }
    }
    else{
        for(Shop s : result){
            if(s.getClientPoints().getPointsSpent() == 0){
                this.shops.remove(s);
            }   
        }
    }


    ptsListAdapter.setCollection(this.shops);
    ptsListAdapter.setFilter(this.activeFilter);

}

This method is called on the result of an async task. I need to remove some elements of the collection before passing to the list adapter.

    11-23 17:39:59.760: E/AndroidRuntime(19777): java.util.ConcurrentModificationException
11-23 17:39:59.760: E/AndroidRuntime(19777):    at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)

Answer

assylias picture assylias · Nov 23, 2012

You can't remove items from a list while iterating over it. You need to use an iterator and its remove method:

for(Iterator<Shop> it = result.iterator(); it.hasNext();) {
    Shop s = it.next();
    if(s.getClientPoints().getPointsSpent() == 0) {
        it.remove();
    }   
}