I am following this codelab Android Kotlin Fundamentals 04.2: Complex lifecycle situations https://codelabs.developers.google.com/codelabs/kotlin-android-training-complex-lifecycle/index.html#4
In tast 5 you simulate app shutdown and use onSaveInstanceState()
When I follow the instructions, but also when I run the solution code, saveInstanceState is not restored after the first app shutdown, but only after the second app shutdown.
The solution code from Codelab: https://github.com/google-developer-training/android-kotlin-fundamentals-apps/tree/master/DessertClickerFinal
And the MainActivity code
class MainActivity : AppCompatActivity() {
private var revenue = 0
private var dessertsSold = 0
private lateinit var dessertTimer : DessertTimer;
private var currentDessert = allDesserts[0]
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.i("onCreate called")
if (savedInstanceState != null) {
revenue = savedInstanceState.getInt(KEY_REVENUE, 0)
dessertsSold = savedInstanceState.getInt(KEY_DESSERT_SOLD, 0)
dessertTimer.secondsCount =
savedInstanceState.getInt(KEY_TIMER_SECONDS, 0)
// Show the next dessert
showCurrentDessert()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
Timber.i("onSaveInstanceState Called")
outState.putInt(KEY_REVENUE, revenue)
outState.putInt(KEY_DESSERT_SOLD, dessertsSold)
outState.putInt(KEY_TIMER_SECONDS, dessertTimer.secondsCount)
}
In the solution code project, I do the following:
- Run the app, click on the dessert (to create data to save)
- Put app to background, kill it
- Open app with recents screen
- onSaveInstanceState is null..
- Put the app in the backgroud again, kill it
- Open app with recents screen
- savedState is restored
This happens every time; After the app is running and shutdown for the first time, nothing happens, after I kill it for the second time, savedState is restored.
I use Android Studio and Kotlin. I shutdown the app using:
adb shell am kill com.example.android.dessertclicker
Or the terminate application button in the Logcat. Both give the same result.
I read that some programmers say you have to call super.onSaveInstanceState after putting the key value pairs to outstate:Bundle, but I just followed the sample code. When I try to call it after, I get the same result anyway.
Does anyone have any clue why this happens? And can anyone tell me if they experience the same behavior when running the solution code?
try to include onRestoreInstanceState. read more about the lifecycle here. But I dont think it save the state if you kill the app... maybe you should better use SharedPreferences?