I am writing an app that stores a value after it get killed by the user. It is stored in the ViewModel
and saved in the onClear
function. I want to be able to reopen the app and see the saved value but when I access this value with the specified key, it comes back as null. Here is my code
package com.example.sharedexpenseapp
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.navigation.NavController
import com.loopj.android.http.AsyncHttpClient
import com.loopj.android.http.TextHttpResponseHandler
import cz.msebera.android.httpclient.Header
class MainActivityViewModel constructor (private val savedState: SavedStateHandle): ViewModel() {
companion object {
private const val NAME= "NAME"
}
//LiveData for HomePageFragment
private val liveName = MutableLiveData<String>(getName().value)
internal val name: LiveData<String>
get() = liveName
internal val orientation = MutableLiveData<Int>()
internal var navController: NavController? = null
//LiveData for LoginFragment
internal val liveNameEditText = MutableLiveData<String>()
internal fun saveName(name: String?) { liveName.value = name; name?.let { savedState.set(NAME, it) }}
private fun getName(): MutableLiveData<String> { return savedState.getLiveData(NAME) }
override fun onCleared() {
liveName.value?.let { saveName(it) }
super.onCleared()
}
}
Most of the functions in my code have been omitted but the savedState part is included. Is there anything that I am doing wrong or misunderstanding?
EDIT:
I now understand that SavedStateHandle
only persists when the system kills the process. Instead of using SavedStateHandle
, is there any other data type or technique that I can use to save data after the user closes the app?
As per official doc on SavedStateHandle
These values will persist after the process is killed by the system and remain available via the same object.
not after user kills the app.
You can either store data in SharedPreference
or local DB