0

I'm currently trying to change the menu item icon on the toolbar programmatically from onCreate(). I'm passing my toolbar object from onCreate() to my method that is ran at startup. If records are found from Firebase query, I'm wanting to change to a new icon drawable.

My toolbar Menu has 3 total items: A search bar and two menu items Here is my stack trace error :

java.lang.IndexOutOfBoundsException: Index: 2131362144, Size: 3
    at java.util.ArrayList.get(ArrayList.java:411)
    at android.support.v7.view.menu.MenuBuilder.getItem(MenuBuilder.java:758)
    at com.google.android.gms.tasks.zzj.run(Unknown Source)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

I've never done this before in an application so I'm unsure of which methods to use to replace the icon. This is what I've tried so far.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    getAllNotifications(toolbar);
}


private void getAllNotifications(Toolbar toolbar){

    db.collection("Users_Profile_Information")
    .document(userID)
    .collection("All_Messages")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if(task.isSuccessful()){
                        if(task.getResult() != null){
                            toolbar.getMenu().getItem(R.id.notifications).setIcon(R.drawable.notification_two);
                        }



                    }
                }
            });
}
exceptionsAreBad
  • 573
  • 2
  • 5
  • 17
  • The `getItem()` method expects an index, not an `R.id`. With an `R.id`, you would use the `findItem()` method instead. – Mike M. Dec 22 '18 at 01:07
  • Thanks! that worked. I looked through a bunch of posts pertaining to my problem but I guess i overlooked that post. – exceptionsAreBad Dec 22 '18 at 01:10
  • No problem. Yeah, it's in my list of common duplicates, so it was easy for me to grab quickly. I'm not sure how easy it was to find originally, though. Anyhoo, glad you got it working. Cheers! – Mike M. Dec 22 '18 at 01:12

1 Answers1

0

If you have 3 menu items:

menu.getItem(0); // 1 item
menu.getItem(1); // 2 item
menu.getItem(2); // 3 item

Android documentations link.

Dmytro Ivanov
  • 1,260
  • 1
  • 8
  • 10