Last Updated: February 25, 2016
· alberovalley

Persisting data between configurations changes: Fragments

When getting data within our fragments we can find that when the configuration (i.e. device orientation) changes, the fragment is re-created with all the data lost (or re-obtained if we're working with remote data). We can prevent it easily with something like this.

public void onSaveInstanceState(Bundle savedInstanceState){
    savedInstanceState.putString(KEY1, myString);
    savedInstanceState.putParcelable(KEY2, myParcelableObject);
public void onRestoreInstanceState(Bundle savedInstanceState) {

  String myString = savedInstanceState.getString(KEY1);
  // myParcelableObject being a field of the fragment class
       myParcelableObject = savedInstanceState.getParcelable(KEY2);
  // maybe call UI methods

public void onStart() {
            // check if myParcelableObject has been loaded from the instance
    if (myParcelableObject != null) {
        // call UI methond or just use the data on the UI
    }else {
        // retrieve data since it's a first execution of the fragment