Search code examples
androidnullpointerexceptionandroid-optionsmenuoncreateoptionsmenu

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.


Solution

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