Last Updated: February 25, 2016
·
2.389K
· 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.

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

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

     @Override
public void onStart() {
    super.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
    }
}