Skip to content
Related Articles

Related Articles

How to Implement On Saved Instance State in Android?

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 29 Dec, 2021

In android, Preserving and restoring an activity’s UI state in a timely fashion across system-initiated activity or application destruction is a crucial part of the user experience. In these cases the user expects the UI state to remain the same, but the system destroys the activity and any state stored in it. The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity. Activities have the ability, under special circumstances, to restore themselves to a previous state using the data stored in this bundle.

What we are going to build in this article?

In this article, we will be using an editText, radio button, and a spinner to take input from users. When the user will rotate the screen in wide mode then the data will be shown using a Toast proving the concept on OnSavedInstanceState. Here is a sample video of what we going to build in this article. Note that we are going to implement this application using Java Langauge.

Step by Step Implementation

Step 1: Creating a new project

  • Open a new project.
  • We will be working on Empty Activity with language as Java. Leave all other options unchanged.
  • You can change the name of the project at your convenience.
  • There will be two default files named activity_main.xml and MainActivity.java.

If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? 

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:gravity="center_horizontal"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit_text"
        android:hint="Enter text"
        android:padding="12dp"
        android:background="@android:drawable/editbox_background"/>
    
    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/radio_group"
        android:orientation="horizontal"
        android:layout_marginTop="16dp">
        
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/rb_true"
            android:text="True"
            android:textSize="24sp"
            android:padding="12dp"/>
        
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/rb_false"
            android:text="False"
            android:textSize="24sp"
            android:padding="12dp"/>
  
    </RadioGroup>
  
    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:padding="12dp"
        android:layout_marginTop="16dp"/>
  
</LinearLayout>


After executing the above code design of the activity_main.xml file looks like this.

Step 3: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




package com.example.savedinstancestate;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
  
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // initialize variables
    EditText editText;
    RadioGroup radioGroup;
    RadioButton rbTrue,rbFalse;
    Spinner spinner;
    String string;
    boolean aBoolean;
    int anInt;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // assign variables
        editText=findViewById(R.id.edit_text);
        radioGroup=findViewById(R.id.radio_group);
        rbTrue=findViewById(R.id.rb_true);
        rbFalse=findViewById(R.id.rb_false);
        spinner=findViewById(R.id.spinner);
  
        // initialize array list
        ArrayList<String> arrayList= new ArrayList<>();
        arrayList.add("Select Position");
        arrayList.add("1");
        arrayList.add("2");
        arrayList.add("3");
  
        // set adapter
        spinner.setAdapter(new ArrayAdapter<>(getApplicationContext()
        , android.R.layout.simple_spinner_dropdown_item,arrayList
        ));
  
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  
            }
  
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // get string value
                string=String.valueOf(s);
            }
  
            @Override
            public void afterTextChanged(Editable s) {
  
            }
        });
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // get boolean value
                aBoolean=checkedId==R.id.rb_true;
  
            }
        });
  
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // get int value
                anInt=position;
            }
  
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
  
            }
        });
  
    }
  
    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        // put string value
        outState.putString("string_value",string);
  
        // put boolean value
        outState.putBoolean("boolean_value",aBoolean);
  
        // Put int value
        outState.putInt("int_value",anInt);
        super.onSaveInstanceState(outState);
    }
  
    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        // get values from saved state
        string=savedInstanceState.getString("string_value");
        aBoolean=savedInstanceState.getBoolean("boolean_value");
        anInt=savedInstanceState.getInt("int_value");
  
        // display toast
        Toast.makeText(getApplicationContext(),string+" - "+ aBoolean+" - "+anInt,Toast.LENGTH_SHORT).show();
        super.onRestoreInstanceState(savedInstanceState);
    }
}


Here is the final output of our application.

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!