Store and Retrieve Fragment state data in Android

Save fragment state data in the onSaveInstanceState method. This is called after onPause(), this is where you will store the data that you want to keep when the user come back to this fragment. In this case, the data is a string saved with the name greeting, savedInstanceState.putString("greeting", "Hello");

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    Log.i(TAG, " onSaveInstanceState.");
    savedInstanceState.putString("greeting", "Hello");
}

Retrieve the fragment state data in the onViewStateRestored method. This is called after onActivityCreated(), this is where you will retrieve the data that’s stored from the onSaveInstanceState. The data was a string and saved with the name greeting, so we get it by calling the getString("greeting") on savedInstanceState.

@Override
public void onViewStateRestored(Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);
    String greeting = (savedInstanceState != null) ? savedInstanceState.getString("greeting") : "null";
    Log.i(TAG, " onViewStateRestored: " + greeting);
}

The data can also be retrieved in the onCreate, onCreateView and onActivityCreated methods because the Bundle savedInstanceState is passed into these methods as well. For example:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        String greeting = (savedInstanceState != null) ? savedInstanceState.getString("greeting") : "null";
    Log.i(TAG, " onCreate: " + greeting);
}

Note: If the onDestroy of the fragment is never called. The Bundle savedInstanceState will be null even if there were data saved in the onSaveInstanceState method. An example of the onDestroy will never called is when you called setRetainInstance(true); in the fragment.

Search within Codexpedia

Custom Search

Search the entire web

Custom Search