I am creating a simple click game that spawns enemies on screen and when the user clicks them, they get points and the enemies are destroyed. I do this with making imageboxs visible and invisible when the user clicks on them. They run on a timer and have a constant loop of spawning.
Currently I want to implement a way the user will start to loose health. So I would like to check if the enemy imagebox is visible, if it is, the player will slowly loose health.
I am confused with creating a timer task that can refresh the UI for this job. I want to be able to check the UI constantly if some images are visible or not. I have made a start on this from my own research but the game crashes when loaded if this is implemented.
Timer to refresh UI:
private Timer mTimer1;
private TimerTask mTt1;
private Handler mTimerHandler = new Handler();
public void onStart() {
mTimer1 = new Timer();
mTt1 = new TimerTask() {
public void run() {
mTimerHandler.post(new Runnable() {
public void run() {
//TODO
final TextView health = (TextView) findViewById(R.id.Health);
health.setText("Health: " + health2);
//Enemy ImageViews
final ImageView enemy1 = (ImageView) findViewById(R.id.enemy1);
final ImageView enemy2 = (ImageView) findViewById(R.id.enemy2);
final ImageView enemy3 = (ImageView) findViewById(R.id.enemy3);
final ImageView enemy4 = (ImageView) findViewById(R.id.enemy4);
//sets imageViews into array
final ImageView[] enemies = new ImageView[4];
enemies[0] = enemy1;
enemies[1] = enemy2;
enemies[2] = enemy3;
enemies[3] = enemy4;
boolean running = true;
while (running) {
if (enemy1.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
if (enemy2.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
if (enemy3.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
if (enemy4.getVisibility() == View.VISIBLE) {
int damage = 1;
health2 = health2 - damage;
health.setText("Health:" + health2);
} else {
// Either gone or invisible
}
}
}
});
}
};
mTimer1.schedule(mTt1, 1, 5000);
}
}
This is the timer task I have created. I would like some clarity to why this crashes my game and how to fix this issue. I have never used timer in this way before so if the problem is obvious that is why I have not noticed it.
I have a lot more code inside the onCreate method and can post if needed. Thank you for all the help and advice for this begineer.
Crash: