Android:NullPointerException: Attempt to invoke interface method on a null object reference

  android, java, nullpointerexception

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

    app:showAsAction="never" />

Then in the MainActivity I create the menu with

public boolean onCreateOptionsMenu(Menu menu) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    boolean do_inc_summary = sharedPreferences.getBoolean("summary", false);
    if (do_inc_summary) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(, 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(

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.

Source: Android Questions