Aniket Thakur
Aniket Thakur

Reputation: 68935

Not able to restore saved instance of activity

Here is my GamePlay Activity code

public class GamePlay extends Activity implements OnClickListener {

private boolean disableSound = false;
//.....
//Code Code
//.....

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //.....
    //Code Code
    //.....
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putBoolean("disableSound", disableSound);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  disableSound = savedInstanceState.getBoolean("disableSound");
  Menu menu = (Menu)findViewById(R.menu.tic_tac_toe);
  MenuItem toggleSoundItemMenu = menu.findItem(R.id.toogle_sound_menu);
  if(disableSound)
      toggleSoundItemMenu.setTitle(R.string.toggle_sound_off_label);
  else
      toggleSoundItemMenu.setTitle(R.string.toggle_sound_on_label);

}

//other functions and code
}

Now on game restart I am restarting the activity. Following code is inside the onClickListener() withing appropriate case

    case R.id.game_play_restart_button:
        Intent restartActivity = new Intent(this,GamePlay.class);
        finish();
        startActivity(restartActivity);
        break;

But still the state does not persist. I disable the sound and restart the game then sound turns back on which is the default behavior. What am I missing? Any suggestion is appreciated.

Upvotes: 0

Views: 906

Answers (1)

k3v1n4ud3
k3v1n4ud3

Reputation: 2994

The savedInstanceState bundle is kept by the system as long as the activity hasn't been destroyed by the system. When you call finish, you destroy the current activity, and the bundle that comes with it. That's the reason why you can't get your boolean back.

You should consider passing this boolean as an extra in the intent like:

restartActivity.putExtra("disableSound", disableSound)

And then on the onCreate of your activity:

getIntent().getBooleanExtra("disableSound", false)

Please note that the last parameter false is just a default value. You can set it to true if that's the behaviour you want.

Upvotes: 1

Related Questions