I'm learning Android development and I'am currently developing a game where little flys appear on the screen and the user has to click on them so they dissapear. But my method for despawning them just gives me this error: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
private void removeFlys() {
int number=0;
while(number < playarea.getChildCount()) {
ImageView muecke = (ImageView) playarea.getChildAt(number);
Date birthdate = (Date) muecke.getTag(R.id.birthdate);
long age = (new Date()).getTime() - birthdate.getTime();
if(alter > 2000) {
playarea.removeView(muecke);
} else {
number++;
}
}
}
this is the xml file where the birthdate tag is defined
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name = "birthdate" type ="id" />
</resources>
This is my code to spawn the flys
private void spawnFlys() {
int width = playarea.getWidth();
int heigth = playarea.getHeight();
int muecke_width = Math.round(x * 50);
int muecke_heigth = Math.round(x * 42);
int left = randomgenerator.nextInt(width - muecke_width);
int top = randomgenerator.nextInt(heigth - muecke_heigth);
ImageView muecke = new ImageView(this);
muecke.setImageResource(R.drawable.fliege);
muecke.setOnClickListener(this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(muecke_width, muecke_heigth);
params.leftMargin = left;
params.topMargin = top;
params.gravity = Gravity.TOP + Gravity.LEFT;
playarea.addView(muecke, params);
muecke.setTag(R.id.birthdate, new Date());
}
And this is where the spawnFlys method gets called
private void timer(){
time = time -1;
float randomNumber = randomgenerator.nextFloat();
double probabilitiy = muecken * 1.5;
if(probability > 1) {
spawnFlys();
if(randomNumber < probability -1) {
spawnFlys();
}
} else {
if (randomNumber < probability) {
spawnFlys();
}
}
removeFlys();
updateScreen();
if(!checkGameDone()) {
if(!checkRoundDone()){
handler.postDelayed(this, 1000);
}
}
}