Skip to content

Instantly share code, notes, and snippets.

@VaidotasK
Created March 25, 2018 22:16
Show Gist options
  • Save VaidotasK/7253cbc02a0d1f6e544959a5e14428dd to your computer and use it in GitHub Desktop.
Save VaidotasK/7253cbc02a0d1f6e544959a5e14428dd to your computer and use it in GitHub Desktop.
Sample of Java code - OnSaveInstanceState/OnCreate/OnRestoreInstanceState
//Saves data before changing activity
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(PLAYER_1_NAME, playerAName);
savedInstanceState.putString(PLAYER_2_NAME, playerBName);
savedInstanceState.putInt(SCORE_A, scorePlayerA);
savedInstanceState.putInt(SCORE_B, scorePlayerB);
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
playerAName = savedInstanceState.getString(PLAYER_1_NAME);
playerBName = savedInstanceState.getString(PLAYER_2_NAME);
scorePlayerA = savedInstanceState.getInt(SCORE_A);
scorePlayerB = savedInstanceState.getInt(SCORE_B);
}
}
//Shows scores of player A and B after changing phone position - portrait to landscape and vice versus
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
playerAName = savedInstanceState.getString(PLAYER_1_NAME);
scorePlayerA = savedInstanceState.getInt(SCORE_A);
displayForPlayerA(scorePlayerA);
displayForPlayerB(scorePlayerB);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment