Android MenuItem not always initialized

69
May 11, 2022, at 04:40 AM

I have an activity with three MenuItem's. I have three variables at the top of the activity class for each MenuItem (e.g. menu1, menu2, menu3).

I initialize the three MenuItems in the onCreateOptionsMenu method like this

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.the_menu, menu);
    menu1 = menu.findItem(R.id.menu_item_1);
    menu2 = menu.findItem(R.id.menu_item_2);
    menu3 = menu.findItem(R.id.menu_item_3);
    
    return true;
}

The problem I am having is every now and then the MenuItems are null. I get this error message: java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.MenuItem.setVisible(boolean)' on a null object reference

I need help finding out why the MenuItem's sometimes are initialized and other times not (around once in every three times I open the activity).

READ ALSO
App is crashing when i click on any item in recyclerview

App is crashing when i click on any item in recyclerview

I was creating a recycler view and trying to create a toast when any item is clicked on using interface(i'm doing for first time)But my app is crashing when i click any item in recycler view

56
Kotlin: Subscribe to Firebase Cloud Messaging(FCM) Topic

Kotlin: Subscribe to Firebase Cloud Messaging(FCM) Topic

I've used the Android (Java) way of doing things before for subscribing to a topic

67
Lib Gdx what is the error and how to solve it?

Lib Gdx what is the error and how to solve it?

When I create a bundle, I get this errorWhen I create an apk or run directly from Android Studio, there are no errors

61