6

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?

6
  • "Then I force-close my app" -- how do you do that? If you are swiping the app off of the overview screen, since that destroys the task, the saved instance state also goes away. It seems like the red square button in Android Studio does the same thing. I've had the best luck using adb. Jun 1, 2020 at 19:21
  • 2
    @CommonsWare Yes I'm swiping the app to simulate force-closing. Wouldn't SavedStateHandle save the state for this scenario? Jun 1, 2020 at 19:25
  • 2
    In that case I do not understand the advantage of using SavedStateHandle. Android doc clearly states: These values will persist after the process is killed by the system and remain available via the same object. Jun 1, 2020 at 19:34
  • 2
    The scenario for saved instance state (whether working with the raw Bundle or SavedStateHandle) is for when the system terminates the process due to low memory conditions, but the user returns to the app quickly (<30 minutes, last I checked). Jun 1, 2020 at 19:42
  • 5
    Huh.. This is very confusing, the docs also led me to expect that the values persist across task instances.
    – Maarten
    Jun 3, 2020 at 10:54

1 Answer 1

2

"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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.