我正在学习Android开发,并且我目前正在开发一款游戏,该游戏的屏幕上只有很少的苍蝇出现,用户必须单击它们才能消失。但是我的派生它们的方法只会给我这个错误:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'long java.util.Date.getTime()'
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++;
}
}
}
这是定义了生日标记的xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name = "birthdate" type ="id" />
</resources>
这是我产生苍蝇的代码
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());
}
这就是spawnFlys方法被调用的地方
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);
}
}
}
答案 0 :(得分:1)
我认为Date birthdate = (Date) muecke.getTag(R.id.birthdate);
返回null尝试将其注销以查看会发生什么情况
答案 1 :(得分:0)
除非您事先调用了<WebView style={{ opacity: 0.99 }} />
,否则getTag
返回的值将始终为null。看来您的布局是父视图内的setTag
列表,因此,在某个时候,您需要在所有这些ImageViews
对象上设置R.id.birthDate
。像这样:
ImageView