I followed the instructions in the following page and created a viewModel, but SavedStateHandle
does not work when I close the app and open it again.
Here is the page:
Saved State module for ViewModel
Here is my view model class:
class UserViewModel(private val state : SavedStateHandle) : ViewModel(){
val userId: LiveData<String> by lazy {
state.getLiveData("userId")
}
fun setUserId(userId : String) {
state["userId"] = userId
}
val user : User by lazy {
User("")
} }
Here is how I use the viewModel in my activity.
val userViewModel : UserViewModel by viewModels()
I even tried this one in my activity, but this did not work either!
val userViewModel: UserViewModel by viewModels {
SavedStateViewModelFactory(
application,
this
)
What should I do to persist data in the SavedStateHandle
? I mean, after opening the app state
is still empty.
Within the documentation that you linked you can read that, under
User-initiated UI-state dismissal
:from https://developer.android.com/topic/libraries/architecture/saving-states#use_onsaveinstancestate_as_backup_to_handle_system-initiated_process_death
So you have misunderstood the intentions and scope of SavedStateHandle and ViewModel. If restoring state after user initiated UI-state dismissal is really important to your app then I suggest starting with focussing on preserving state to disk (DB, file, SharedPreferences, etc) and restoring when appropriate - then later on look at facilitating smoother UX by leveraging features such as SavedStateHandle in ViewModel.