java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.ImageView.setImageResource(int)'

时间:2016-06-08 16:37:14

标签: java android nullpointerexception

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.ImageView.setImageResource(int)'

我想制作第一个活动转移的图标/图像或转移到第二个活动但上面显示的错误。

这是我在第一个actvty中的源代码:

 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;
    }
}

1 个答案:

答案 0 :(得分:1)

变量titleImg可能为null。您应该调试函数以查看它是否实际上是从setContentValues()中的第一个语句中找到的。