menu.findItem(R.id.*) is null- Android

ravensgo picture ravensgo · Sep 18, 2014 · Viewed 9.1k times · Source

I am trying to enable/disable a refresh button when certain things happen in my app, but I get a null pointer exception that I can't figure out. I am setting a boolean addingRefresh or removingRefresh to true depending on the situation and then calling invalidateOptionsMenu() to enable or disable the button, however the menu item is returned null. I have searched the internet for why this may be but can't find anything.

Code for onCreateOptionsMenu() (called when invalidateOptionsMenu() is called)

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (addingRefresh) {
        //below line as well as other similar line cause exceptions
        menu.findItem(R.id.action_refresh).setEnabled(true);
        addingRefresh = false;
    } else if (removingRefresh) {
        menu.findItem(R.id.action_refresh).setEnabled(false);
        removingRefresh = false;
    } else if (addingLoading) {

    }
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_activity_actions, menu);
    return super.onCreateOptionsMenu(menu);
}

Thanks for any help!

Answer

Eric Cochran picture Eric Cochran · Sep 18, 2014

Here is some cleaned up code for what you are trying to accomplish:

private MenuItem mMenuItem;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    final MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_activity_actions, menu);
    mMenuItem = menu.findItem(R.id.action_refresh)
    return true;
}

private void setMenuItemEnabled(boolean enabled) {
    mMenuItem.setEnabled(enabled);
}

Hope that helps!