Reputation: 7102
I'm working on an Android game which fires an onDraw()
method 30 times per second.
In this method I am iterating through an ArrayList
of objects and drawing them with an object.Draw()
method I created.
My problem is, I want to add objects to this ArrayList
in the game's onTouchEvent()
, but I sometimes get the following error:
java.util.ConcurrentModificationException
I know what's happening here, the onTouchEvent()
fires when I touch the screen, so objects are being added to my ArrayList
, but sometimes this happens as my onDraw()
method is firing, which iterates through my ArrayList
, and this causes the exception. Makes sense.
My question is, how can I add objects to my ArrayList
when I touch the screen if it's being iterated through in my onDraw()
method? Can I try to detect touch events in my onDraw()
method? This way there will never be a problem. This is my first time programming games for Android, how is this kind of thing usually handled?
Upvotes: 0
Views: 57
Reputation: 69228
It looks like you're accessing and modifying the list from different threads. Try synchronizing access to the list (so only one thread will have access to it at a time).
Another option might be to use CopyOnWriteArrayList.
Upvotes: 1