How to Handle Configuration Changes in Android?
Last Updated :
25 May, 2025
Sometimes the Android device undergoes configuration changes, during application runtime. While the device undergoing configuration changes all the activities and fragments are recreated. This restarting of the application while configuration changes help the application to adapt to new configurations by automatically reloading application alternative resources that match the new device configuration. And while happening this recreation of activities and fragments the data and UI need to be restored. The traditional way of doing this is using bundles and handling the callbacks of onSavedInstanceStae().
Refer to How to Restore Data on Configuration Changed in Android using Bundles?
Now have a look a the following video of how the data is lost during configuration changes if not handled properly. So in this discussion, it's been demonstrated how we can restore the data and update the UI after configuration changes.
Scope of ViewModel
By referring to the following image, it's observed that the objects of ViewModel are scoped to lifecycle owner passed to the ViewModelProvider when getting ViewModel. The ViewModel object remains in the memory for the entire lifecycle of the lifecycle owner. Here the lifecycle owner is the MainActivity.kt which has its own lifecycle.
In case of activity, when the activity has finished the scope of the ViewModel object is destroyed. In the case of the Fragment, when it's detached.
The ViewModel object created when the system calls the onCreate() method. It may be called several times, throughout the life of activity. Such as when the device is rotated. The ViewModel object still exists when it was requested for the first time until the activity is finished and destroyed.
Steps to handle the configuration changes in android
Step 1: Create an empty activity Android Studio project
Create an empty activity Android Studio project and select Kotlin as the programming language.
Refer to Android | How to Create/Start a New Project in Android Studio?
Step 2: Working with activity_main.xml file
The main layout of the application contains one button and one TextView. To implement the same invoke the following code inside the activity_main.xml file.
activity_main.xml:
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
tools:ignore="HardcodedText">
<TextView
android:id="@+id/textView"
style="@style/TextAppearance.MaterialComponents.Headline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="INCREMENT"
app:layout_constraintEnd_toEndOf="@+id/textView"
app:layout_constraintStart_toStartOf="@+id/textView"
app:layout_constraintTop_toBottomOf="@+id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>
Design UI:
Step 3: Creating ViewModel for the activity
The ViewModel class inherits the ViewModel as the superclass. And the required data members and the member functions are created inside it, in which the scope of all data members and the functions remain throughout the life of activity. To implement the ViewModel create a class called MyViewModel.kt and invoke the following code.
MyViewModel.kt:
Kotlin
package org.geeksforgeeks.demo
import androidx.lifecycle.ViewModel
class MyViewModel : ViewModel() {
// number to increment and show on UI
var number = 0
// function when called increments the value of number
fun addNumber(): Int = number++
}
Step 4: Working with MainActivity.kt
In the MainActivity.kt file, the object of the ViewModel is created using the ViewModelProvider, of the lifecycle owner. Here the lifecycle owner is MainAactivity.kt file. To implement the same invoke the following code inside the MainActivity.kt file.
MainActivity.kt:
Kotlin
package org.geeksforgeeks.demo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// create instance of the viewModel of the Custom MyViewModel for the activity MainActivity.kt
val myViewModel: MyViewModel = ViewModelProvider(this)[MyViewModel::class.java]
// create instances of the UI elements
val button: Button = findViewById(R.id.button)
val textView: TextView = findViewById(R.id.textView)
textView.text = myViewModel.number.toString()
button.setOnClickListener {
// trigger the increment
// function to increment the value
myViewModel.addNumber()
// set the updated value of number to the TextView
textView.text = myViewModel.number.toString()
}
}
}
Output:
Similar Reads
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 t
3 min read
How to Listen to Orientation Change in Android? In Android, applications can have orientations of types namely portrait and landscape. By default, every new project when created comes with a portrait orientation. However, this can be changed to landscape or semi. In the case of the semi, both portrait and landscape orientation is supported by the
3 min read
How to Build Android Applications with Gradle? There are several contemporary build automation technologies available nowadays that may be utilized to create a quicker build when creating a project. Gradle is one of these modern-day automation technologies. Gradle is now used by Android to automate and control the build process while also defini
8 min read
How to Debug Database in Android? The Android Debug Database library is a useful tool for troubleshooting databases and shared preferences in Android apps. In this article we would be looking forward to using this library and get our hand on it, so continue reading, and indulge. First thing's first, What's Exactly an Android Debug D
3 min read
How to Change Application's Starting Activity in Android? Many times while building an android application. We have to change the default activity of our application to another activity that we have created within our android studio project. So that we can set that custom activity to the starting activity of our application. In this article, we will take a
2 min read