Using SavedStateHandle with a shared ViewModel

Viewed 467

I have a shared ViewModel that is shared across my MainActivity and all my fragments so it basically serves as a shared data model for my entire android app.

I basically access it like this everywhere:

viewModel = new ViewModelProvider(this).get(SharedViewModel.class);

Now I'd like to start saving this state using the SavedStateHandle, so I add the following constructor to my model:

public class SharedViewModel extends ViewModel {

  public SharedViewModel(SavedStateHandle savedStateHandle) {
    this.savedStateHandle = savedStateHandle;
    String blah = savedStateHandle.get("blah");
  }

Whenever I change blah I call set() on the savedStateHandle:

  public void setBlah(String b) {
    blah = b;
    savedStateHandle.set("blah", b);
  }

The savedStateHandle is actually provided in the constructor: the viewModel is created with it, but every time I obtain a value from it savedStateHandle.get("blah"); it always returns null even though I have stored the value in there in the previous run of the app (which I'm launching from the Android Studio).

How can I save my state in this shared ViewModel?

My dependencies:

implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.navigation:navigation-fragment:2.3.5'
implementation 'androidx.navigation:navigation-ui:2.3.5'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.savedstate:savedstate:1.1.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.3.1'
0 Answers
Related