Google is committed to advancing racial equity for Black communities. See how.

Saved State module for ViewModel   Part of Android Jetpack.

As mentioned in the Saving UI States article, ViewModel objects can handle configuration changes so you don't need to worry about state in rotations or other cases. However, if you need to handle system-initiated process death, you may want to use onSaveInstanceState() as backup.

UI State is usually stored or referenced in ViewModel objects, not activities; so using onSaveInstanceState() requires some boilerplate that this module can handle for you.

When the module is set up, ViewModel objects receive a SavedStateHandle object via its constructor. This is a key-value map that will let you write and retrieve objects to and from the saved state. These values will persist after the process is killed by the system and remain available via the same object.

Setup and usage

When using Fragment 1.2.0 or its transitive dependency Activity 1.1.0, the default factory for ViewModel instances support passing the appropriate SavedStateHandle to your ViewModel without any additional configuration.

Kotlin

// Use the Kotlin property extension in the fragment-ktx / activity-ktx artifacts
val vm: SavedStateViewModel by viewModels()

Java

SavedStateViewModel vm = new ViewModelProvider(this)
        .get(SavedStateViewModel.class);

After that your ViewModel can have a constructor that receives a SavedStateHandle:

Kotlin

class SavedStateViewModel(private val state: SavedStateHandle) : ViewModel() { ... }

Java


public class SavedStateViewModel extends ViewModel {
    private SavedStateHandle mState;

    public SavedStateViewModel(SavedStateHandle savedStateHandle) {
        mState = savedStateHandle;
    }
    ...
}

When providing a custom ViewModelProvider.Factory instance, you can enable usage of SavedStateHandle by extending AbstractSavedStateViewModelFactory.

Storing and retrieving values

The SavedStateHandle class has the methods you expect for a key-value map:

  • get(String key)
  • contains(String key)
  • remove(String key)
  • set(String key, T value)
  • keys()

Also, there is a special method: getLiveData(String key) that returns the value wrapped in a LiveData observable.

Acceptable classes

Type/Class Array support
double double[]
int int[]
long long[]
String String[]
byte byte[]
char char[]
CharSequence CharSequence[]
float float[]
Parcelable Parcelable[]
Serializable Serializable[]
short short[]
SparseArray
Binder
Bundle
ArrayList
Size (only in API 21+)
SizeF (only in API 21+)

Additional resources

For further information about the Saved State module for ViewModel, consult the following resources.

Codelabs