0

Edit : Solved, I detailed the solution in an answer.

I might be missing something easy and I think the solution will be quite simple but I can't find it.

My problem is that I want to change the text of my menu items (displayed in a navigation drawer) dynamically, but when i try to use findItem(R.id.item1) I get a null value.

Here is my code where I try to change the text :

// call invalidateOptionsMenu(); to refresh
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    menu.findItem(R.id.item1).setTitle("Some random text");
    return super.onPrepareOptionsMenu(menu);
}

And my menu :

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
    android:id="@+id/group_users"
    android:checkableBehavior="single">
    <item
        android:id="@+id/item1"
        android:icon="@drawable/util_bleu_24dp"
        android:title="@string/item1"/>
    <item
        android:id="@+id/item2"
        android:icon="@drawable/util_rose_24dp"
        android:title="@string/item2"/>
</group>

When I try to execute it I get the error :

java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.MenuItem.setTitle(java.lang.CharSequence)' on a null object reference

Can someone help me find what's wrong with this please ?

Guitare
  • 69
  • 10
  • you can try this solution i hope it work with you . https://stackoverflow.com/questions/7066657/how-to-change-menu-item-text-dynamically-in-android – Nour Eldien Mohamed Jan 29 '20 at 22:05
  • yeah I have seen this post during my research, It inspired me to do my code but they don't talk about my problem. Thanks anyway – Guitare Jan 29 '20 at 23:01
  • did you try to add this android:enabled="true" to your items ? – Nour Eldien Mohamed Jan 29 '20 at 23:12
  • hum, I can't find it in the link you gave me, I tried based on your comment, just adding "android:enabled=true" to my menu items in xml but it don't change anything – Guitare Jan 29 '20 at 23:24

1 Answers1

0

After creating a new project to try to do it clean, I figured out I forgot to add this part in my code :

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.personnal_menu, menu);
    return true;
}

And this created another menu distinct from the one I was trying to modify, and worked perfectly on this new menu. So in fact I was just searching the wrong problem.

Solution was to do this (anywhere in the activity) :

NavigationView navigationView = findViewById(R.id.nav_view_left);
Menu menu = navigationView.getMenu();
MenuItem item1 = menu.findItem(R.id.item1);
item1.setTitle("Some random text");

I hope this can help anybody doing the same mistake as me.

Guitare
  • 69
  • 10