I know this has been asked many times before but I've gone through all the previous questions and not been able to apply the answers to my particular problem.
I have a SwitchPreference in my settings that switches on or off a particular set of activities. That set of activities in included in the menu, so I want to be able to hide the item when it's not valid.
In my menu, the item is defined by
<item
android:id="@+id/action_most_recent_summary"
android:orderInCategory="20"
android:visible="true"
android:title="@string/action_most_recent_summary"
app:showAsAction="never" />
Then in the MainActivity I create the menu with
@Override
public boolean onCreateOptionsMenu(Menu menu) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean do_inc_summary = sharedPreferences.getBoolean("summary", false);
if (do_inc_summary) {
menu.findItem(R.id.action_most_recent_summary).setVisible(true);
}
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
Sometimes it doesn't work!
Sometimes the app crashes and I get the following error in the logcat
java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.MenuItem.setVisible(boolean)' on a null object reference
at com.example.cgpagerv2.MainActivity.onCreateOptionsMenu(MainActivity.java:52)
Line 52 is the menu.findItem line. So I think it's telling me either "menu" or "do_inc_summary" is null, but I don't understand why.