Menu.findItem (R.id. *) - null - Android

I try to enable / disable the refresh button when something happens in my application, but I get an exception from the null pointer that I cannot understand. I set boolean addingRefresh or removingRefresh to true depending on the situation and then call invalidateOptionsMenu() to enable or disable the button, however the menu item returns null. I searched on the Internet why it could 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!

+8
source share
3 answers

Here is some cleared code for what you are trying to execute:

 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 this helps!

+6
source

Just to eliminate doubts. You have to use

 menu.findItem(R.id.menuId); 

after inflating the menu

+5
source

For me, the cause of the problem was incorrect import: android.widget.SearchView

instead of androidx.appcompat.widget.SearchView

and take care of the namespace application: actionViewClass

0
source

Source: https://habr.com/ru/post/1202830/


All Articles