Jack
Jack

Reputation: 2053

Options Menu null at runtime

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.

Upvotes: 1

Views: 3303

Answers (2)

Muthukrishnan Rajendran
Muthukrishnan Rajendran

Reputation: 11622

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

Upvotes: 6

SpaceBison
SpaceBison

Reputation: 3131

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.

Upvotes: 4

Related Questions