Q:

Why Android Action menu item not update

I have created an action bar item for messages and when a new message is received it should be updated. The problem is when I refresh the activity it sometimes shows the icon as a new message and sometimes it shows as no new messages. It happens randomly. It is not updating correctly. I checked How to update a menu item shown in the ActionBar?
But couldn't fix my problem. I realize the problem is onCreateOptionMenu execute while oncreate. How can I delay that ?
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.loggedmenu, menu);

    int no;

    try {
        no = Integer.parseInt(noOfmsgs);
    } catch (NumberFormatException e) {
        no = 0;
    }

    if (no > 0) {
        menu.findItem(R.id.messages)
                .setIcon(R.drawable.ic_action_new_email);
    } else {
        menu.findItem(R.id.messages).setIcon(R.drawable.ic_action_email);
    }

    return true;
}

A:

As you said, onCreateOptionsMenu is called once the Activity is created and that's all, at least that you call invalidateOptionsMenu() to get this method again. However, you can have a global variable in the activity to update your items later as follows:  
// global var menu
private Menu mMenu;

// onCreate, onResume, etc.

// Init the var
@Override
public boolean onCreateOptionsMenu(Menu menu) {
     this.mMenu = menu;
     getMenuInflater().inflate(R.menu.loggedmenu, menu);
     return true;
}  

Then, after doing an AsyncTask, a Thread or whatever you do to update the noOfmsgs value, call this method:  
// update the items
private void updateMenuItems() {
    int no;
    try {
        no = Integer.parseInt(noOfmsgs);
    } catch (NumberFormatException e) {
        no = 0;
    }
    if (no > 0) {
        mMenu.findItem(R.id.messages).setIcon(R.drawable.ic_action_new_email);
    } else {
        mMenu.findItem(R.id.messages).setIcon(R.drawable.ic_action_email);
    }
} 

