[英]How to retain app EditText data when Android app process restarts
When we deny any permission in the settings page while our app is alive.当我们在应用程序运行时拒绝设置页面中的任何权限时。 Android kills our app. Android 杀死了我们的应用程序。 And re-create everything (fragments and activities).并重新创建一切(片段和活动)。 viewModel is also cleared. viewModel 也被清除。 This cause the typed text in any edit text field gets cleared.这会导致在任何编辑文本字段中键入的文本被清除。 FYI, While creating the fragment, the savedInstanceState will be non-null.仅供参考,在创建片段时,savedInstanceState 将是非空的。 But i see in some apps, like Gmail, Maps, the form data is retained while process restart.但是我在某些应用程序中看到,例如 Gmail、地图,在进程重新启动时会保留表单数据。 Can anyone please explain how to retain the edit text data while process recreate?谁能解释在重新创建过程时如何保留编辑文本数据?
You can retain ViewModel
data using SavedStateHandle
.您可以使用SavedStateHandle
保留ViewModel
数据。
class MyViewModel(private val state: SavedStateHandle) : ViewModel() { ... }
SavedStateHandle
is a key-value map where you can save your EditText
content. SavedStateHandle
是一个键值映射,您可以在其中保存您的EditText
内容。 The value will persist even after the process is killed by the System.即使进程被系统杀死,该值仍将保持不变。 You can retrieve the value using the same key.您可以使用相同的键检索值。
To set the value:要设置值:
savedStateHandle["text"] = text
and retrieve it back simply use the below statement:并将其取回只需使用以下语句:
savedStateHandle["text"]
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
// store your data
outState.putString("some code", "111")
outState.putString("some code1", "222")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// read your data
savedInstanceState.getString("some code")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.