Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
How to Restore Data on Configuration Changed in Android using Bundles?
Next article icon

How to Restore Data on Configuration Changed in Android using Bundles?

Last Updated : 24 Jan, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Restore Data on Configuration Changed in Android using Bundles

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.
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"     tools:context=".MainActivity"     tools:ignore="HardcodedText">      <EditText         android:id="@+id/editText"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginStart="16dp"         android:layout_marginTop="32dp"         android:layout_marginEnd="16dp"         android:hint="Enter Something"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent" />      <Button         android:id="@+id/decrementB"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginStart="32dp"         android:layout_marginTop="32dp"         app:icon="@drawable/ic_remove"         app:iconGravity="textStart"         app:iconPadding="0dp"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/editText" />      <TextView         android:id="@+id/counterText"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="0"         android:textSize="24sp"         app:layout_constraintBottom_toBottomOf="@+id/incrementB"         app:layout_constraintEnd_toStartOf="@+id/incrementB"         app:layout_constraintHorizontal_bias="0.497"         app:layout_constraintStart_toEndOf="@+id/decrementB"         app:layout_constraintTop_toTopOf="@+id/incrementB" />      <Button         android:id="@+id/incrementB"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="32dp"         android:layout_marginEnd="32dp"         app:icon="@drawable/ic_add"         app:iconGravity="textStart"         app:iconPadding="0dp"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintTop_toBottomOf="@+id/editText" />  </androidx.constraintlayout.widget.ConstraintLayout> 

Output: 

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.
Kotlin
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView  class MainActivity : AppCompatActivity() {      // instances of all the UI elements     lateinit var editText: EditText     lateinit var counterText: TextView     lateinit var incrementB: Button     lateinit var decrementB: Button      // counter to increment or        // decrement the counter text     var countInt: Int = 0      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          // register all the UI elements with            // their appropriate IDs         editText = findViewById(R.id.editText)         incrementB = findViewById(R.id.incrementB)         decrementB = findViewById(R.id.decrementB)         counterText = findViewById(R.id.counterText)          // handle the increment button         incrementB.setOnClickListener {             if (countInt >= 0) {                 countInt++                 counterText.text = countInt.toString()             }         }          // handle the decrement button         decrementB.setOnClickListener {             if (countInt > 0) {                 countInt--                 counterText.text = countInt.toString()             }         }     }      override fun onSaveInstanceState(outState: Bundle) {         super.onSaveInstanceState(outState)          // put the unique key value with the data           // to be restored after configuration changes         outState.putInt("counterData", countInt)     }      override fun onRestoreInstanceState(savedInstanceState: Bundle) {         super.onRestoreInstanceState(savedInstanceState)          // get the stored data from the bundle using the unique key         countInt = savedInstanceState.getInt("counterData")          // update the UI         counterText.text = countInt.toString()     } } 

Output:


Next Article
How to Restore Data on Configuration Changed in Android using Bundles?

A

adityamshidlyali
Improve
Article Tags :
  • Technical Scripter
  • Kotlin
  • Android
  • Technical Scripter 2020

Similar Reads

    How to Handle Configuration Changes in Android?
    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 configuratio
    3 min read
    How to Change Password of User in Android using Firebase?
    In many apps, we got a feature to login using our email and password. Sometimes it happens that we forget the password and most of the time there reset our password. Here we are going to implement the same feature to Reset our password using Firebase Authentication. You may refer to the following ar
    3 min read
    How to Update Data in API using Retrofit in Android?
    We have seen reading data from API as well as posting data to our database with the help of the API. In this article, we will take a look at updating our data in our API. We will be using the Retrofit library for updating our data in our API.  What we are going to build in this article?  We will be
    6 min read
    How to Get the Connection Information in Android using Jetpack Compose?
    Many times while building an android application we require connection-related information about the android device such as IP address, link speed, and others within our android application. In this article, we will take a look at How to obtain connection-related information in the android applicati
    4 min read
    How to pre populate database in Android using SQLite Database
    Introduction : Often, there is a need to initiate an Android app with an already existing database. This is called prepopulating a database. In this article, we will see how to pre-populate database in Android using SQLite Database. The database used in this example can be downloaded as Demo Databas
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences