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

不打扰是莪最后的温柔 提交于 2019-12-20 04:13:04

问题


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

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

回答1:


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.



来源:https://stackoverflow.com/questions/37708204/java-lang-nullpointerexception-attempt-to-invoke-virtual-method-void-android-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!