I have an Android application with the following menu item in one of the Activities (which concerns handling a list of names and mac numbers):
<item android:id="@+id/menu_sort_tagg"
android:icon="@android:drawable/ic_menu_sort_by_size"
android:title="@string/menu_sort_list" >
<menu>
<group android:checkableBehavior="single">
<item android:id="@+id/sort_by_name"
android:title="@string/sort_by_name" />
<item android:id="@+id/sort_by_mac"
android:title="@string/sort_by_mac" />
</menu>
</item>
and as the application state changes, I want to be able to pre-check which item in the sort options list that was used last time with the following code:
((MenuItem)findViewById(R.id.sort_by_name)).setChecked(true);
The problem is that this specific line gives me a runtime exception. Does anyone have a clue why?
A look at the log reveals that the runtime exceptions is triggered by a null pointer exception. By changing the code in this way:
MenuItem mi = (MenuItem)findViewById(R.id.sort_by_name);
mi.setChecked(true);
it becomes clear that the exception occurs in the seconds statement, i.e., the MenuItem mi is null. So why fails the first statement to bring a pointer to the correct MenuItem?
You can't do findViewById()
for a menu, because it's a menu, not a view. And you can change menu state when it's being created or prepared. For example, if you create an options menu, you can do it in the Activity: onPrepareOptionsMenu()
method:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.sort_by_name).setChecked(true);
//Also you can do this for sub menu
menu.getItem(firstItemIndex).getSubMenu().getItem(subItemIndex).setChecked(true);
return true;
}