小编典典

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'voidandroid.widget.ImageView.setImageResource(int)'[重复]

java

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

阅读 365

收藏
2020-11-26

共1个答案

小编典典

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

2020-11-26