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)
How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.
What Causes ConcurrentModificationException. The ConcurrentModificationException generally occurs when working with Java Collections. The Collection classes in Java are very fail-fast and if they are attempted to be modified while a thread is iterating over it, a ConcurrentModificationException is thrown.
ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.
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();
}
}
You get this error typically when
You modify the collection directly while it is iterating over the collection
or even worse when
one threads modifies the collection, while another iterates over it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With