1

I am changing the drawable of a specific menu item when certain actions are made within my app.

Everything works as it should except for when I try and do this in the onCreate method of my Activity.

I am using the following method:

menu.findItem(R.id.favorite).setIcon(R.drawable.ic_action_icons8_star_filled_100);

In an onClick event and it works flawlessly.

But when I use the same method in my onCreate, it gives me the following eror:

java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem(int)' on a null object reference

This is the code I am using to inflate the menu

private Menu menu;

--------------------


 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.image_details, menu);

        this.menu = menu;

        return super.onCreateOptionsMenu(menu);
    }

Any ideas? thanks.

Jack
  • 2,043
  • 7
  • 40
  • 69

2 Answers2

6

You can use onPrepareOptionsMenu(this will get a call whenever the menu will about to visible). You are getting null pointer because onCreateOptionsMenu will call after onCreate so your menu object will be null.

@Override
 public boolean onPrepareOptionsMenu(Menu menu) {

    MenuItem favoriteItem = menu.findItem(R.id.favorite);

    favoriteItem.setIcon(getResources().getDrawable(R.drawable.drawable.ic_action_icons8_star_filled_100)); 

    return super.onPrepareOptionsMenu(menu);
 }
Roger Alien
  • 3,040
  • 1
  • 36
  • 46
Muthukrishnan Rajendran
  • 11,122
  • 3
  • 31
  • 41
3

According to the Activity lifecycle, onCreateOptionsMenu is called after onResume, so when onCreate is called, the field menu has not yet been set. If you move the call to onPrepareOptionsMenu it should work.

SpaceBison
  • 2,525
  • 1
  • 21
  • 38