IgorGanapolsky
IgorGanapolsky

Reputation: 26821

Android SavedStateHandle doesn't save in ViewModel

I have a ViewModel which takes a SavedStateHandle parameter. I am saving a String in there like this:

    private fun saveString(str: String) {
        state.set(KEY_STRING, str)
    }

Then I force-close my app and relaunch it, and want to retrieve the saved string like this:

fun getSavedString(): String? {
        return state.get<String>(KEY_String)
    }

However, it always returns null. Any ideas how to use SavedStateHandle correctly?

Upvotes: 6

Views: 2383

Answers (1)

Aliaksandr Chaulytka
Aliaksandr Chaulytka

Reputation: 104

"Then I force-close my app and relaunch it.."

I guess you kill the app completely =)

One of the way for reproducing saveState case you need:

  1. Enable developers mode and check Don't keep activities
  2. Process limit -> No background processes
  3. Send you app in background (SavedStateHandle will saved)
  4. Restore app from background or tap on the icon of app (SavedStateHandle will restored)

Another the easiest way:

  1. Send you app in background
  2. Tap terminate (Logcat)

enter image description here

  1. Restore app from background or tap on the icon of app

Also you should use SavedStateViewModelFactory if you want to receive SavedStateHandle in ViewModel

Upvotes: 3

Related Questions