Background
I've encountered a strange issue when testing my level-select screen.
I have 20 levels and display the 'select buttons' for them in 2 rows of 10 (I did this rather than display 4 rows of 5 so it leaves room for a 'select level' graphic at the bottom of the screen an a banner ad at the top).
I display 2 control buttons (left and right) as only 5 buttons (wide) will fit onto the screen. When you press the controls, the level buttons shift left/right so the user can scroll through all 20 levels.
So, my buttons are a batch of quads (derived from a custome 'QuadBatch' class - this class has a 'numberToDraw' variable which, as the name suggests, tells the drawing method how many quads are in this batch to be drawn.
Problem
When the left key is pressed, within the onTouchEvent() method, I set a (previously declared) boolean 'movingLeft' to true, and movingRight to false & vice-versa for when the right button is pressed. (When the finger is lifted, they are both set to false).
Then, on the rendering thread (on which I'm running my game logic), I have a method which basically says:
if (movingLeft){
for (int x=0;if x < buttonBatch.numberToDraw-1;x++){
moveButtonsLeft(x*2); //this method utilises an array of coordinates arranged as x, y, x, y etc... therefore, I need to use 0, 2, 4, 6 for X coordinates, hence the '-1' after number to draw
}
}
So, with 20 buttons, there is an array of length 40 holding their coordinates, (indices 0-39), I make sure that the loop doesn't go over 38 (the last X coordinate) because 19 x 2 is 38.
99% of the time, this works. No problem. But now and again I get an Index Array Out of Bounds error. And, when I look at logcat, sure enough, it's saying the array length is 40 (correct) but that the index being accessed is also 40 (which is clearly not right).
Threads?
I'm wondering if this could have anything to do with sync problems between the UI thread and the main GL Rendering thread?
What I've attempted to fix the issue
I've declared my onTouchEvent() method as 'synchronized', as well as the method that does the moving of my level buttons and have tested this for about 20 minutes with no crashes. I'm not sure if this has made any difference though as the issue is so intermittent.
Any ideas why this array would intermittently be out of bounds? Am I on the right track regarding the thread safety issue?