When i run the application and touch the bitmap sometimes appliaction craches
Here is the error:
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at com.example.Game.GFXSurface$GameSurface.run(GFXSurface.java:135)
at java.lang.Thread.run(Thread.java:864)
And the code where it craches and if i remove balls.remove and balls.add everything works fine but than it won’t generate new ball, and in run method everything works fine with remove and add:
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
GameSurface gamesurface = new GameSurface(this);
x = event.getX();
y = event.getY();
Bitmap ball = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
for (int i = 0; i < 4; i++)
if (ourSurfaceView.MouseOnDot(ball) && x >= ballX[i]
&& x <= ballX[i] + 72) {
balls.remove(i);
balls.add(i, gamesurface.RandomBall());
ChangingY[i] = 0;
if (speed <= 7)
speed += 0.1;
}
return false;
}
here is the method where is balls.get
@Override
public void run() {
for (int j = 0; j < 4; j++) {
balls.add(j, RandomBall());
}
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawRGB(02, 02, 150);
for (int i = 0; i < 4; i++) {
ballX[i] = i * 155;
canvas.drawBitmap(balls.get(i), ballX[i], ChangingY[i],
null);
if (ChangingY[i] <= canvas.getHeight()) {
ChangingY[i] += 1 * speed;
} else if (ChangingY[i] > canvas.getHeight()) {
ChangingY[i] = 0;
if (speed <= 5)
speed += 0.25;
balls.remove(i);
balls.add(i, RandomBall());
}
}
// }
ourHolder.unlockCanvasAndPost(canvas);
}
}
Error means that index which you use to access ArrayList is bigger than ArrayList size.
Try instead of for (int i = 0; i < 4; i++) use for (int i = 0; i < balls.size(); i++)
Or when you use balls.remove(i) check first if i < balls.size