0

I have to dynamically change the onCreateOptionsMenu items. I am fetching the items from a web service. But the problem is that the service is called in onCreate() and in an AsyncTask class so before the data from the service arrives onCreateOptionsMenu gets called and returns NullPointerException.

Here's how I am calling the function:

@Override

public boolean onCreateOptionsMenu(Menu menu) {

    // super.onCreateOptionsMenu(menu);

    getMenuInflater().inflate(R.menu.action_bar_menu, menu);
    item = menu.findItem(R.id.CurrentUser);
    UserName = con.getResources().getString(R.string.WelcomeUser) + " "
            + UserName + "!";
    item.setTitle(UserName);

    if (IsCorporateAccount) {
        menu.getItem(6).setVisible(true);
    } else {
        menu.getItem(6).setVisible(false);
    }

    objGetBalanceDetails.CreateMenu(menu);

    // Menu menu1 = null;
    // menu1.findItem(R.id.Home).setVisible(false);
    return true;
}
Ragunath Jawahar
  • 19,513
  • 22
  • 110
  • 155
Hussain Marvi
  • 455
  • 1
  • 5
  • 17

1 Answers1

0

you can grab menu in onCreateOptions menu

private Menu mMenu;

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.myMenu, menu);
    mMenu = menu;
    }

and after making changes in your menu i.e adding or removing items , you can call invalidateOptionsMenu(); (support for api > 11) to update your menu.

Waqar Ahmed
  • 5,005
  • 2
  • 23
  • 45
  • the function that filling the optionsmenu is another java file and is fetching data from a web service.The problem is the delay.. if i toggle a break point and produce a delay then the whole thing is working fine.. – Hussain Marvi Apr 28 '14 at 05:44
  • you can create something like delegate that will notify you when asyntask finishd. so after then immedeiately create your menu. – Waqar Ahmed Apr 28 '14 at 05:48