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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37708204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:42:01  来源:igfitidea点击:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference

javaandroidnullpointerexception

提问by jDmendiola

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference

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

I want to make the icon/image of the first activity transfer or move to the second activity but this error above show up.

我想让第一个活动的图标/图像转移或移动到第二个活动,但出现上述错误。

This is my source code in the first actvty:

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

 public void next (View view){
    Intent intent = new Intent(this, Products.class);
    intent.putExtra("Button ID", btnId);
    startActivity(intent);
}

then in the Second actvty

然后在第二个活动中

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

采纳答案by Robo

The variable titleImg is possibly null. You should debug into the function to see if it's actually found from the first statement in setContentValues() or not.

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