How to Restore Data on Configuration Changed in Android using Bundles?
In Android, if the configuration of the application changes, for example when the android screen is rotated, then some data is lost and reset. Especially, the data from the variables. So this issue can be solved by overriding the functions onSaveInstanaceState() and onRestoreInstanceState(). So in this article, it’s been discussed how this issue can be resolved in detail using the flow chart, so as to understand when these above functions are called. Note that we are going to implement this project using the Kotlin language.
Below is a flow chart represents how the methods are called and data is restored and updated in the UI:
Step by Step Implementation
Step 1: Create an empty activity project
- Using Android Studio create a new empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio?, to know how to create an empty activity Android Studio project.
Step 2: Working with the activity_main.xml file
- The main layout of the application containing EditText, and one TextView, and two Buttons, which increment and decrement the value of the TextView.
- To implement the UI invoke the following code inside the activity_main.xml file.
Step 3: Working with the MainActivity.kt file
- In the MainActivity,kt file the two functions onSaveInstanceState(outState: Bundle) and onRestoreInstanceState(savedInstanceState: Bundle) has to be overridden, the onSaveInstanceState function puts the data to bundle named outState, and onRestoreInstanceState function receives the data using Bundle named savedInstanceState. Refer to the flow chart provided above to get clear flow.
- To implement the same invoke the following code inside the MainActivity.kt file.
- Comments are added inside the code to understand the code in more detail.