How to handle ConcurrentModificationException in Android

Viewed 15270

Im trying to delete item from a ArrayList. Some times it pops an exception, java.util.ConcurrentModificationException.

First I tried to remove them by array_list_name.remove(i), but it failed and some people were asked to use Iterator instead. So my current code is as follows:

for (Iterator<Collectable> iter = array_list_name.iterator(); iter.hasNext();) {
   Collectable s = iter.next();
   if (s.equals(array_list_name.get(id))){
       iter.remove();
       return true;
   }
}

And I call array_list_name inside onDraw() function in view. My view is a SurfaceView. Can anyone suggest me how to delete items from ArrayList without getting this error?

4 Answers

Have you ever thought to use Vector List ? If you need a thread-safe implementation, you should use Vector instead of ArrayList. Vector list's usage is same with ArrayList. Just change its type with Vector.

Unsafe usage

ArrayList<FutureTask> futureTasks;

Change with

Vector<FutureTask> futureTasks;

That's all.

Related