When I click home button onPause method is called but when I call application in front onResume is called and than it crashes.
There is code when index is out of bouds:
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawRGB(02, 02, 150);
fingerx = (x - (Gball.getWidth() / 2));
fingery = (y - (Gball.getHeight() * 2));
for (int i = 0; i < balls.size(); i++) { // here...
ballX[i] = i * 155;
canvas.drawText("" + score, 40, 100, paint);
canvas.drawBitmap(balls.get(i), ballX[i], ChangingY[i],
null);
Error is:
FATAL EXCEPTION: Thread-9140
java.lang.ArrayIndexOutOfBoundsException: length=4; index=4
at com.example.mygame.GFXSurface$GameSurface.run(GFXSurface.java:199)
at java.lang.Thread.run(Thread.java:864)
I know index should be 5 here but if it is than application doesn’t even start
OnResume:
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
ourSurfaceView.resume();
}
public void resume() {
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
Run method:
@Override
public void run() {
for (int j = 0; j < 4; j++) {
balls.add(j, RandomBall());
}
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(100);
paint1.setStyle(Style.FILL);
paint1.setColor(Color.RED);
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawRGB(02, 02, 150);
fingerx = (x - (Gball.getWidth() / 2));
fingery = (y - (Gball.getHeight() * 2));
for (int i = 0; i < balls.size(); i++) {
ballX[i] = i * 155;
canvas.drawText("" + score, 40, 100, paint);
canvas.drawBitmap(balls.get(i), ballX[i], ChangingY[i],
null);
if (x != 0 && y != 0 && mode == 0) {
if (fingerx < 0) {
canvas.drawBitmap(Gball, 0, fingery, null);
} else if (fingery < 0) {
canvas.drawBitmap(Gball, fingerx, 0, null);
}
else
canvas.drawBitmap(Gball, fingerx, fingery, null);
checkForCollision(i);
}
if (ChangingY[i] <= canvas.getHeight()) {
ChangingY[i] += 1 * speed;
} else if (ChangingY[i] > canvas.getHeight()) {
ChangingY[i] = -72;
if (speed <= 11)
speed += 0.25;
removeAndAdd(this, i);
}
}
ourHolder.unlockCanvasAndPost(canvas);
}
}
You are looping based on the size of
ballsbut within your loop you are accessing bothballXandChangingYusing the indexi. IfballXis smaller than balls then you will get an ArrayIndexOutOfBoundsException.Since you are updating the values within the array
ballXduring the loop, then you probably want to create a new array using the size ofballsbefore the loop starts:Don’t know what ChangingY is, but you will need to make sure that is also at least as big as balls.