How can I fix this error? "Java.lang.IndexOutOfBoundsException"

I am trying to make a game with andengine library .

When Sprite Enemy1Sprite reaches the top of the camera and I turn it off, this exception is thrown:

 java.lang.IndexOutOfBoundsException Invalid Index 12 size is 12 

I need to disconnect Enemy1Sprite because it continues to create bullet sprites from the camera.

This is the code.

Class enemy1:

  package es.uah.juegomentos; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.opengl.texture.region.TextureRegion; public class Enemy1 extends Sprite { boolean abajo = true; public Enemy1(TextureRegion pTextureRegion) { super(0, 0, pTextureRegion); this.setPosition(JuegoMentosActivity.RANDOM.nextInt(JuegoMentosActivity.CAMERA_WIDTH), -10); TimerHandler Enemy1fire = new TimerHandler(0.75f, true, enemigo1fireCallback); JuegoMentosActivity.getmGameScene().registerUpdateHandler(Enemy1fire); } @Override protected void onManagedUpdate(float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); float y = getY(); if (y >= 275) {abajo = false;} if (abajo) {y = y + pSecondsElapsed * 125.0f;} else {y = y - pSecondsElapsed * 125.0f;} this.setPosition(getX(), y); if (getY()<-10){this.getParent().detachChild(this);} } ITimerCallback enemigo1fireCallback = new ITimerCallback(){ @Override public void onTimePassed(TimerHandler pTimerHandler) { bala1 mbala1; mbala1 = new bala1(getX()+(64*1/2),getY()+64,JuegoMentosActivity.getMbala1Texture().getTextureRegion(),true); JuegoMentosActivity.getmGameScene().attachChild(mbala1); } }; } 

Create a new enemy in the scene:

  //Creamos el sprite del enemigo uno ITimerCallback enemigo1CreatorCallback = new ITimerCallback(){ @Override public void onTimePassed(TimerHandler pTimerHandler) { mEnemy1Sprite = new Enemy1(mEnemy1Texture.getTextureRegion()); mGameScene.attachChild(mEnemy1Sprite); } }; TimerHandler Enemy1Creator = new TimerHandler(3.0f, true, enemigo1CreatorCallback); mGameScene.registerUpdateHandler(Enemy1Creator); 

thanks

0
source share
3 answers

You really answered your question - Marcelo is right, the problem is not in the code you sent, where you make the detachChild call - you need to call this in the Update Thread, as in

 runOnUpdateThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub yourScene.detachChild(yourEnemySprite); } }); 
+1
source

This suggests that your actual array size is 12, so your last index is 11. But you are trying to access index 12, which does not exist. Try to find the line that throws this error. Make a condition there if size of index is >= size of array brake .

You can also try using try{}catch(IndexOutOfBondException e){} and continue the process.

+1
source

detach the object in the onManagedUpdate scene.

0
source

Source: https://habr.com/ru/post/1496156/


All Articles