Search code examples
androidkotlinandroid-activitysaveload

Kotlin - Load and save data in activities when minimize or kill app


I'm working on my first kotlin app with several activities. Each activity is composed of fields that the user fills in and saved into an SQLitedatabase I need help on when to save and reload data.

What I do :

In each activity, I save data when going back or when calling another activity.

binding.myButton.setOnClickListener{
    saveData()    
    val intent = Intent(this, MyActivity::class.java)
    startActivity(intent)
}

And I reload all the data on onCreate() and onResume().

override fun onResume() {
    super.onResume()   
    loadData()
}

How to manage and determine when user minimize app ? I can use onStop() but it's also called when activity ends.

Same question when user kills the app ? onDestroy() is also used when activity ends

Thanks for your help


Solution

  • There's a specific function for this. It's called onSaveInstanceState and onRestoreInstanceState. These will be called when the app is minimized, and you can save your state into a Bundle. This Bundle will be written to disk by the OS, and when you return you will be passed in a Bundle with the same values. Doing it in these functions will also ensure that it works correctly for Activity restarts and various other corner cases. Do not use onResume or onPause directly.

    (BTW- onResume pairs with onPause. onStart pairs with onStop. You wouldn't do something in onStop and onResume, you'd do it in onPause and onResule or onStart and onStop. You don't mix the two pairs).