Skip to content

Instantly share code, notes, and snippets.

@LarsEliasNielsen
Created November 7, 2014 15:05
Show Gist options
  • Save LarsEliasNielsen/f99c30761e86da1f7e1f to your computer and use it in GitHub Desktop.
Save LarsEliasNielsen/f99c30761e86da1f7e1f to your computer and use it in GitHub Desktop.
Saving data in activity instance state
/**
* When the user changes orientation in the activity, the activity is redrawn.
* To prevent loss of my variables (like what question is active) I save a variable into
* the instance state of my activity.
* When this is done, I can prevent the user fron detecting the redraw of my activity.
*/
public class MainActivity extends Activity {
// My variable I want to keep.
public int currentQuestionNumber = 0;
// Label for my variable; used when saving to instance state.
private static final String CURRENT_QUESTION = "current_question";
@Override
protected void onCreate(Bundle savedInstanceState) {
// My onCreate method in my activity ...
// Check if state is already set.
if (savedInstanceState != null) {
// If saved state exists, then get the variable from instance state.
currentQuestionNumber = savedInstanceState.getInt(CURRENT_QUESTION);
}
}
// ...
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// When the user changes orientation, this is run.
// Save variable to instance state.
outState.putInt(CURRENT_QUESTION, currentQuestion);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment