Save activity state in android studio kotlin
To save the state of an activity in Android using Kotlin, you can use the onSaveInstanceState method and the Bundle class.
Here is an example to save the state of an activity:
class MyActivity : Activity() { private var myVariable: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { // Restore the value of myVariable from the saved state myVariable = savedInstanceState.getString("myVariable") } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) // Save the value of myVariable in the outState bundle outState.putString("myVariable", myVariable) } }
In the above example, in MyActivity.kt class we create one variable named as myVariable.
In onCreate method, we check if the savedInstanceState bundle is not null then we store the value in the myVariable
In the onSaveInstanceState method, we save the value of myVariable in the outState bundle.
The onSaveInstanceState method is called when the activity is about to be destroyed, so this is a good place to save the state of the activity.
The savedInstanceState bundle is passed to the onCreate method when the activity is recreated, so this is a good place to restore the state of the activity.
I hope this helps! Let me know if you have any questions.
0 Comments