Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android menu, throwing IndexOutOfBoundsException while running onPrepareOptionsMenu

When I try to update my MenuItem in menu I recieve IndexOutOfBoundsException.

I've added menu_item in xml and I can see it when enable() == false.

My code:

public boolean onPrepareOptionsMenu(Menu menu) {
    if ( enable() ) {
        MenuItem menuItem= menu.getItem(R.id.menu_item);
        menuItem.setEnabled(true);
    }
    return super.onPrepareOptionsMenu(menu);
}

How to deal with the problem?

Cheers.

like image 901
neciu Avatar asked Nov 09 '11 16:11

neciu


2 Answers

Just had the same problem. Happens if you accidentally use the getItem() instead of findItem().

MenuItem menuItem = menu.findItem(R.id.menu_item);
like image 156
Daniel Lerps Avatar answered Oct 31 '22 13:10

Daniel Lerps


Probably you need to Clean your project to update the values of R. If you prefer another way, you can do

for(int i = 0; i<menu.size();++i)
{
    if(menu.getItem(i).getItemId() == R.id.menu_item)
         MenuItem menuItem = menu.getItem(i);
}

or opt for a more beautiful

menu.findItem(R.id.menu_item);

like image 45
Makers_F Avatar answered Oct 31 '22 14:10

Makers_F