3

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;
    }
}
zekromWex
  • 280
  • 1
  • 4
  • 17
  • 1
    Post the whole code of the 2nd activity. Where is your method `setContentValues();` called? It must be in `onCreate` **after** `setContentView`. – Vucko Jun 08 '16 at 16:39
  • Yes. I called it in onCreate and after setContentView – zekromWex Jun 08 '16 at 16:48
  • 1
    where is your `setContentView`? show all the code. You need to double check the ids in your layout. `(ImageView) findViewById(R.id.imageView_result_title);` is apparently returning null - either you haven't inflated a layout (forgot to call `setContentView`), or you're calling `setContentValue` before the layout is inflated, or it doesn't actually have a view with id `R.id.imageView_result_title`. – trooper Jun 08 '16 at 17:06
  • Yeah. I solved the problem already. Thanks :) – zekromWex Jun 09 '16 at 02:17

1 Answers1

3

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.

Robo
  • 612
  • 3
  • 7