I have two ArrayList’s that I am using, one for the enemy sprites and the other for the bullets. When I run the app it occasionally crashes on the emulator and within a few levels it crashes on a device upon collision. The log keeps telling me I have a simple ListIterator error. I wanted to know how would I implement the ListIterator. I have not been using a ListIterator, I searched around to find information and examples but I am a bit confused on how to actually do it. The add() function is called in the onTouch method of my view class and the collision takes place inside of my thread class in its own collision methods.
Log:
07-20 19:57:46.604: ERROR/AndroidRuntime(234): Uncaught handler: thread Thread-9 exiting due to uncaught exception
07-20 19:57:46.613: ERROR/AndroidRuntime(234): java.util.ConcurrentModificationException
07-20 19:57:46.613: ERROR/AndroidRuntime(234): at java.util.AbstractList$SimpleListIterator.next(AbstractList.java:64)
07-20 19:57:46.613: ERROR/AndroidRuntime(234): at com.android.hitmanassault.HitmanView$HitmanThread.startGame(HitmanView.java:333)
07-20 19:57:46.613: ERROR/AndroidRuntime(234): at com.android.hitmanassault.HitmanView$HitmanThread.gameStart(HitmanView.java:290)
07-20 19:57:46.613: ERROR/AndroidRuntime(234): at com.android.hitmanassault.HitmanView$HitmanThread.updateGame(HitmanView.java:393)
07-20 19:57:46.613: ERROR/AndroidRuntime(234): at com.android.hitmanassault.HitmanView$HitmanThread.run(HitmanView.java:237)
Checks Collision:
private void startGame(){
synchronized(mSurfaceHolder){
for(Beam bullet: beam){
for(Sprite sprite: sprites){
if(checkCollision(sprite, bullet)){
sprites.remove(sprite);
beam.remove(bullet);
mScore = mScore + 1;
break;
}
}
}
}
}
Collision Method:
public boolean checkCollision(Sprite sprite, Beam bullet){
boolean retValue = false;
int SpriteX = sprite.getX();
int SpriteY = sprite.getY();
int SpriteXS = sprite.getX() + sprite.getWidth();
int SpriteYS = sprite.getY() + sprite.getHeight();
int BeamX = bullet.getX();
int BeamY = bullet.getY();
int BeamXS = bullet.getX() + bullet.getBitmap().getWidth();
int BeamYS = bullet.getY() + bullet.getBitmap().getHeight();
if ((BeamX >= SpriteX && BeamX <= SpriteXS) || (BeamXS >= SpriteX && BeamXS <= SpriteXS)) {
if ((BeamY >= SpriteY && BeamY <= SpriteYS) || (BeamYS >= SpriteY && BeamYS <= SpriteYS)) {
retValue = true;
}
}
return retValue;
}
If you add an element to the list while another thread iterating the list, you will get ConcurrentModificationException.
You can try ConcurrentLinkedQueue, but depending on your requirement on consistency model of the game, you should rethink the architecture.
This is the problem.
Quick fix is you could gather all element you want to remove then remove them after for loop.