-2

I'm trying to change the title of one of my actionbar menu items. When the user isn't logged in it says Login which is the normal title for it, but once the user logs in I want it to change to logout. What I have right now was just to test if I could get it to work but whenever I run it with the code to change the title it crashes.

Here's the code:

public MenuItem logout;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        background = findViewById(R.id.status);
        status = findViewById(R.id.image); 
        logout = (MenuItem) findViewById(R.id.menu_login);
        logout.setTitle("Blah");
        new CheckStatusTask().execute();
    }
tshepang
  • 12,111
  • 21
  • 91
  • 136
Adonai
  • 73
  • 3
  • 13
  • Read the logcat and check out why it's crashing (the line numbers should help) – keyser Jan 26 '13 at 02:01
  • @Keyser i believe the exception is java.lang.NullPointerException – Adonai Jan 26 '13 at 02:04
  • You're trying to find the menu item in the wrong place. It's always going to be null because `R.id.menu_login` is part of the menu, not the Activity layout. – A--C Jan 26 '13 at 02:07
  • @A--C How would i go about finding it? – Adonai Jan 26 '13 at 02:11
  • iagreen's answer works, also read [this](http://stackoverflow.com/questions/8279981/how-can-i-change-action-bar-actions-dynamically). – A--C Jan 26 '13 at 02:22

2 Answers2

3

It is crashing because the MenuItem does not exist in the view hierarchy, it is only rendered when the menu is created or displayed. You need to put your code in either onCreateOptionsMenu or OnPrepareOptionsMenu, depending on which makes sense for you -- onCreateOptionsMenu is called once when the menu is first displayed, OnPrepareOptionsMenu is called every time it is displayed.

and inside those functions, you can find your menu item with

logout = (MenuItem) menu.findViewById(R.id.menu_login);
iagreen
  • 31,470
  • 8
  • 76
  • 90
  • @Adonai Without a logcat, who knows where it is crashing. You could have multiple issues. – iagreen Jan 26 '13 at 02:24
  • Yes sorry i was going to post the error but i was reading A--C comment. I believe the error is com.android.internal.view.menu.MenuBuilder cannot be cast to android.view.View which i think is caused because when i put the code you gave me in the onCreateOptionMenu it told me to cast it to View without it would through an error. – Adonai Jan 26 '13 at 02:30
-2

I figured out how to fix this. What i did was make two menu xml files and then in the onCreateOptionsMenu i put the if statement to check whether the user is logged in or not and chose the correct menu to go with it.

Adonai
  • 73
  • 3
  • 13