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

标签 java android nullpointerexception

<分区>

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

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

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

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

然后在第二个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;
    }
}

最佳答案

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

关于java.lang.NullPointerException : Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37708204/

相关文章:

java - 停止所有 Awt/Swing 线程和监视器以及其他东西,以便只剩下主线程

java - 获取 Formatter.format() String 中占位符的数量

android - 当按下后退按钮或方向改变时,带 map 的 fragment 会使应用程序崩溃

android - 在 Activity 生命周期中每次需要时都调用 findViewById 好吗?

java - 从批处理文件中终止从 Java 启动的进程

android - 使用 Ionicframework 创建本地存储(设备,而非缓存)

java - 如何在类中正确实例化一个公共(public)类+数据结构以便其他对象可以使用它?

java - Java 模拟 UNIX 文件系统中的空指针异常

c# - 从字节数组创建 BitmapImage

java - 如何为 Serializable 生成 serialVersionUID?