Question

I'm writing an application, which has a menu with buttons and an image. I press the button and label of the button changes from "Record track" to "Stop recording". The issue is when I rotate my device, the activity with buttons gets killed by the OS. So, I understood that I have to save my data before it's get killed in onSaveInstanceState method and then restore it in my onCreate method. Something like this:

@Override
public void onSaveInstanceState(final Bundle saveInstanceState) {
    saveInstanceState.putSerializable("image", image);
    saveInstanceState.putSerializable("buttonState", isRecording);

}

And:

if (savedInstanceState != null) {                                
    isRecording = savedInstanceState.getBoolean("buttonState");  

    if (menu != null) {                                          
        MenuItem recordButton = menu.getItem(R.id.track);

        if (!isRecording) {
            recordButton.setTitle(R.string.rec_track_label);     
        } else {
            recordButton.setTitle(R.string.stop_rec_track_label);
        }
    }                                                            

    Image = (Image)savedInstanceState.getSerializable("image");

} 

And while it perfectly restores my image, I still have issues with the menu: for some reason it always stays "null", so it will never change label of my button despite that it should be recreated every time, when Activity starts and I save it in a private object of my Activity:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    new MenuInflater(this).inflate(R.menu.actions, menu);
    this.menu = menu;
    return (super.onCreateOptionsMenu(menu));
}

Any ideas what am I doing wrong? Thanks.

Was it helpful?

Solution

You should move your menu != null block into onPrepareOptionsMenu:

public boolean onPrepareOptionsMenu(Menu menu)
{
    MenuItem recordButton = menu.findItem(R.id.track);

    if (isRecording) {
        recordButton.setTitle(R.string.rec_track_label);     
    } else {
        recordButton.setTitle(R.string.stop_rec_track_label);
    }
}

As this method is called directly before the menu is being shown to the user.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top