How to Implement OnSavedInstanceState in Android?
Last Updated :
08 Feb, 2023
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.
In this article, we will be using an editText, a 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.
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.
Step 2: Working with the XML Files
Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"
android:hint="Enter text"
android:padding="12dp" />
<RadioGroup
android:id="@+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"
android:text="True"
android:textSize="24sp" />
<RadioButton
android:id="@+id/rb_false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"
android:text="False"
android:textSize="24sp" />
</RadioGroup>
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:padding="12dp" />
</LinearLayout>
Step 3: Working with the MainActivity 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
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);
}
}
Kotlin
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
// initialize variables
lateinit var editText: EditText
lateinit var radioGroup: RadioGroup
lateinit var rbTrue: RadioButton
lateinit var rbFalse: RadioButton
lateinit var spinner: Spinner
lateinit var string: String
var aBoolean = false
var anInt = 0
override fun onCreate(savedInstanceState: Bundle?) {
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
val arrayList = ArrayList<String>()
arrayList.add("Select Position")
arrayList.add("1")
arrayList.add("2")
arrayList.add("3")
// set adapter
spinner.adapter = ArrayAdapter(applicationContext, android.R.layout.simple_spinner_dropdown_item, arrayList)
editText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
// get string value
string = s.toString()
}
override fun afterTextChanged(s: Editable) {}
})
radioGroup.setOnCheckedChangeListener { group, checkedId -> // get boolean value
aBoolean = checkedId == R.id.rb_true
}
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
// get int value
anInt = position
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
}
override fun onSaveInstanceState(outState: Bundle) {
// 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 fun onRestoreInstanceState(savedInstanceState: Bundle) {
// get values from saved state
string = savedInstanceState.getString("string_value").toString()
aBoolean = savedInstanceState.getBoolean("boolean_value")
anInt = savedInstanceState.getInt("int_value")
// display toast
Toast.makeText(applicationContext, "$string - $aBoolean - $anInt", Toast.LENGTH_SHORT)
.show()
super.onRestoreInstanceState(savedInstanceState)
}
}
Here is the final output of our application.
Output:
Similar Reads
How to Implement onBackPressed() in Fragments in Android? In Android, the Fragment is the part of the Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. onBac
3 min read
How to Implement Loading AlertDialog in Android? AlertDialog is defined as the small window that shows a particular message to the user when the user performs or commits certain action. In this article, we are going to build a simple android application in which we learn how to implement a Loading AlertDialog that means whenever the user clicks on
6 min read
How to Implement Press Back Again to Exit in Android? The 'Back' button has many different uses in many different android apps. While some app developers use it to close their apps, some use it to traverse back to the app's previous activity. Many apps require the user to press the 'Back' button two times within an interval to successfully close the ap
2 min read
How to Save Switch Button State in Android? In Android, a Switch is a type of button that lets the user toggle between two actions or instances. In general, a Switch is used for selecting one between two options that can be invoking any actions or functions. In this article, we are going to see how we can save the state of the Switch Button i
3 min read
How to Use Static Method in Android? Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. In this article, we are going to see how we can implement static methods in Android. We will be creating static
5 min read