When we deny any permission in the settings page while our app is alive. Android kills our app. And re-create everything (fragments and activities). viewModel is also cleared. This cause the typed text in any edit text field gets cleared. FYI, While creating the fragment, the savedInstanceState will be non-null. But i see in some apps, like Gmail, Maps, the form data is retained while process restart. Can anyone please explain how to retain the edit text data while process recreate?
CodePudding user response:
You can retain ViewModel
data using SavedStateHandle
.
class MyViewModel(private val state: SavedStateHandle) : ViewModel() { ... }
SavedStateHandle
is a key-value map where you can save your EditText
content. 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"]
CodePudding user response:
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")
}