Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 567
ravensgo Avatar asked Sep 18 '14 01:09

ravensgo


2 Answers

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!

like image 134
Eric Cochran Avatar answered Oct 21 '22 14:10

Eric Cochran


Just for clearing the doubt. You should use

menu.findItem(R.id.menuId);

after inflating the menu

like image 6
Arshad Avatar answered Oct 21 '22 12:10

Arshad