Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentModificationException when drawing on SurfaceView?

Tags:

android

Say I have an ArrayList of "blob" objects, which I cycle through and draw then onto the canvas.

     for (blob b:myBlobList)
     {
         canvas.drawCircle(b.X, b.Y, b.Size, paint);
     }

Also I have an onTouchListener that adds a new blob object whenever the surface is touched.

      if (event.getAction() == android.view.MotionEvent.ACTION_DOWN)
        {
          myBlobList.add(new blob());
          myBlobList.get(myBlobList.size()-1).X = event.getX();
          myBlobList.get(myBlobList.size()-1).Y = event.getY();;
        }

Yet together they cause a ConcurrentModificationException error. What would be your suggestion, how should I fix that?

Simply adding

try{ ... } catch (ConcurrentModificationException e) {}

Makes the screen/canvas flicker when this exception happens and it goes happen a lot. :)

Thanks!

like image 818
Roger Travis Avatar asked Aug 01 '26 04:08

Roger Travis


2 Answers

It seems that you add a new blob to your list while iterating over that list. One simple workaround would be to make a copy of the list before the loop. If you add items while iterating they will not be taken into account.

List<Blob> myBlobCopy = new ArrayList<Blob>(myBlobList); //copies the content
for (Blob b : myBlobCopy) {
    canvas.drawCircle(b.X, b.Y, b.Size, paint);
}
like image 191
assylias Avatar answered Aug 03 '26 17:08

assylias


You can use CopyOnWriteArrayList for your Blobs

like image 30
Alexander Kulyakhtin Avatar answered Aug 03 '26 19:08

Alexander Kulyakhtin