问题描述
我有一个带有 SavedStateHandle
参数的 ViewModel.我正在像这样保存一个字符串:
私人乐趣 saveString(str: String) {state.set(KEY_STRING, str)}
然后我强制关闭我的应用程序并重新启动它,并想像这样检索保存的字符串:
有趣的 getSavedString():字符串?{返回 state.get(KEY_String)}
然而,它总是返回 null.任何想法如何正确使用 SavedStateHandle?
然后我强制关闭我的应用并重新启动它.."
我猜你完全杀死了应用 =)
重现saveState
案例的方法之一:
- 启用开发者模式并检查
不要保留活动
- 进程限制 ->
无后台进程
- 在后台向您发送应用程序(
SavedStateHandle
将保存) - 从后台恢复应用程序或点击应用程序图标(
SavedStateHandle
将恢复)
另一种最简单的方法:
- 在后台向您发送应用
- 点击终止 (Logcat)
- 从后台恢复应用或点击应用图标
如果你想,你也应该使用 SavedStateViewModelFactory
在 ViewModel
SavedStateHandle
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?
"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:
- Enable developers mode and check
Don't keep activities
- Process limit ->
No background processes
- Send you app in background (
SavedStateHandle
will saved) - Restore app from background or tap on the icon of app (
SavedStateHandle
will restored)
Another the easiest way:
- Send you app in background
- Tap terminate (Logcat)
- Restore app from background or tap on the icon of app
这篇关于Android SavedStateHandle 不保存在 ViewModel 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!