I am trying to set a specific username to a specific menu item, then get it using
LoggedUser = (String) menu.getItem(R.id.User).getTitle().toString();
like :
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.User).setTitle("username");
LoggedUse0r=(String) menu.getItem(R.id.User).getTitle().toString();
invalidateOptionsMenu();
return super.onPrepareOptionsMenu(menu);
}
I declared
invalidateOptionsMenu();
in different methods like
onCreate(), onStart(), onResume()
However, my app crashes and gives me this exception:
11-02 07:44:52.112 8714-8714/com.example.prof_mohamedatef.listview E/AndroidRuntime: FATAL EXCEPTION: main java.lang.IndexOutOfBoundsException: Invalid index 2131492986, size is 4 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251) at java.util.ArrayList.get(ArrayList.java:304) at android.support.v7.view.menu.MenuBuilder.getItem(MenuBuilder.java:729) at com.example.prof_mohamedatef.listview.Booking_hotels.onPrepareOptionsMenu(Booking_hotels.java:194) at android.app.Activity.onPreparePanel(Activity.java:2570) at android.support.v4.app.FragmentActivity.onPrepareOptionsPanel(FragmentActivity.java:532) at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:521) at android.support.v7.view.WindowCallbackWrapper.onPreparePanel(WindowCallbackWrapper.java:93) at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onPreparePanel(AppCompatDelegateImplBase.java:355) at android.support.v7.app.AppCompatDelegateImplV9.preparePanel(AppCompatDelegateImplV9.java:1380) at android.support.v7.app.AppCompatDelegateImplV9.doInvalidatePanelMenu(AppCompatDelegateImplV9.java:1633) at android.support.v7.app.AppCompatDelegateImplV9.access$100(AppCompatDelegateImplV9.java:93) at android.support.v7.app.AppCompatDelegateImplV9$1.run(AppCompatDelegateImplV9.java:129) at android.os.Handler.handleCallback(Handler.java:725) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5283) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) at dalvik.system.NativeStart.main(Native Method)
Can any body tell me what's the relation between getting String of item's title and this type of exception:
IndexOutOfBoundsException:
your response will be appreciated, Thanks in advance
Try this.
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.your_menu, menu);
MenuItem item = menu.findItem(R.id.your_menu_item);
String loggedInUser = item.getTitle().toString();
return true;
}