-1

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.

TrapezeArtist
  • 777
  • 1
  • 13
  • 38

1 Answers1

0

You are trying to access item before it is inflated, instance will be available after inflation

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    boolean do_inc_summary = sharedPreferences.getBoolean("summary", false);
    //inflate first
    getMenuInflater().inflate(R.menu.menu_main, menu);
    //then access
    if (do_inc_summary) {
        menu.findItem(R.id.action_most_recent_summary).setVisible(true);
    }
    return true;
}
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37
  • That seems to have stopped the crashes, but the desired function doesn't work. The item in the menu is permanently visible or invisible, depending on whether I set android:visible to true or false and regardless of what I do in the Settings page. – TrapezeArtist Feb 25 '21 at 15:05