Finditem () cannot find menu stuck in NullPointerException

I am stuck changing some properties in the options menu in onCreateOptionsMenu() . FindItem () seems to return null, although I'm sure the menu item reference is correct. My code is as follows:

  @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_profile, menu); MenuItem leftie = menu.findItem(R.id.menu_profile); leftie.setIcon(R.drawable.ic_menu_mapmode); leftie.setTitle(R.string.back_map); leftie.setIntent(authIntent); return true; } 

I really don't know what could be there. Thanks in advance:)

EDIT: I forgot to include the real issue.

+4
source share
4 answers

You can specify the name and image for this menu item in XML.

 <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/newsItem" android:icon="@drawable/news_tab" android:title="@string/menu_news"/> <item android:id="@+id/dryiceItem" android:icon="@drawable/dryice_tab" android:title="@string/menu_dryice"/> </menu> 

and can set the intent on menuItem as follows:

 @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.newsItem: // start News activity //write your intent here. break; case R.id.dryiceItem: //start another activity //write your intent here. break; } } 
+3
source

I get it. The line referencing the menu index, R.menu.activity_profile , was the wrong way, so it inflated an empty menu. I changed the line to R.menu.layout , and now it works as expected.

 System.out.println(menu.size()); MenuItem leftie = menu.findItem(R.id.menu_profile); System.out.println(leftie); leftie.setIcon(R.drawable.ic_menu_mapmode); leftie.setTitle(R.string.back_map); leftie.setIntent(authIntent); 
+1
source

I also had this when I had a submenu that was not properly nested in element tags, e.g.

 <item /> <menu> </menu> 

or

  <item > <menu> </menu> <item> 
0
source

Typecast your findItem statement with MenuItem

  MenuItem leftie = (MenuItem) menu.findItem(R.id.menu_profile); 
-1
source

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


All Articles