这个问题已经在这里有了答案: > findViewByID returns null 28个
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“ void android.widget.ImageView.setImageResource(int)”
我想转移第一个活动的图标/图像,或移到第二个活动,但是上面显示了此错误.
这是我在第一幕中的源代码:
public void next (View view){
Intent intent = new Intent(this, Products.class);
intent.putExtra("Button ID", btnId);
startActivity(intent);
}
然后在第二幕
btnId = getIntent().getIntExtra("Button ID", btnId);
setContentValues();
}
private void setContentValues() {
ImageView titleImg = (ImageView) findViewById(R.id.imageView_result_title);
View view = (View)findViewById(R.id.layout_goals_goals);
switch (btnId) {
case R.id.imageButton_goals_car:
titleImg.setImageResource(R.drawable.car);
break;
case R.id.imageButton_goals_education:
titleImg.setImageResource(R.drawable.education);
break;
case R.id.imageButton_goals_health:
titleImg.setImageResource(R.drawable.health);
break;
case R.id.imageButton_goals_house:
titleImg.setImageResource(R.drawable.house);
break;
case R.id.imageButton_goals_saving:
titleImg.setImageResource(R.drawable.savings);
break;
case R.id.imageButton_goals_travel:
titleImg.setImageResource(R.drawable.travel);
break;
default:
break;
}
}
解决方法:
变量titleImg可能为空.您应该调试该函数以查看是否实际上是从setContentValues()的第一条语句中找到的.