I am making an android game that spawns enemy sprites at a certain interval at the top of the screen. There are no syntax errors, but when I run the game it crashes because of this function:
public void updateEnemies() {
if (numEnemiesCreated == numVisibleEnemies) {
if (timeLastCreatedEnemy + 1000 < System.currentTimeMillis()) {
timeLastCreatedEnemy = System.currentTimeMillis();
boolean createdNewEnemy = false;
for (int i = 0; i < this.numVisibleEnemies; i++) {
if (createdNewEnemy == false) {
if (holderEnemy[i].isDisposed()) {
this.generateNewEnemy(i);
createdNewEnemy = true;
}
}
}
}
for(int i = 0; i<numVisibleEnemies; i++){
if(!holderEnemy[i].isDisposed()){
holderEnemy[i].move();
}
}
} else {
holderEnemy[numEnemiesCreated] = new Enemy(context, 0, 0);
numEnemiesCreated++;
}
}
I have tried everything, I just can’t get it to work! Here is my log cat crash report:
05-25 18:49:13.031: W/dalvikvm(6736): threadid=9: thread exiting with uncaught exception (group=0x40015578)
05-25 18:49:13.035: E/AndroidRuntime(6736): FATAL EXCEPTION: Thread-10
05-25 18:49:13.035: E/AndroidRuntime(6736): java.lang.NullPointerException
05-25 18:49:13.035: E/AndroidRuntime(6736): at com.jlennon.gametest.EnemySpawn.updateEnemies(EnemySpawn.java:49)
05-25 18:49:13.035: E/AndroidRuntime(6736): at com.jlennon.gametest.MainGamePanel$AnimationThread.update(MainGamePanel.java:94)
05-25 18:49:13.035: E/AndroidRuntime(6736): at com.jlennon.gametest.MainGamePanel$AnimationThread.run(MainGamePanel.java:61)
Since the uncaught exception you’re getting is a
NullPointerException, you will need to check that every element inside ofholderEnemyis instantiated to its proper type. You can’t dereferencenull– which is what is given by default in an array.To belabor the point a bit, if you take an array of elements such as:
that is not enough to instantiate the array. You will need to loop over the array and create new
Enemys for each element. Otherwise, you’ll need to guarantee that, within the bounds of [0,numVisibleEnemies), your array elements are properly instantiated.(Note that I’m guessing at the object type, but the principle applies.)