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 TextWatcher in Android?
If an application contains a login form to be filled by the user, the login button should be disabled (meaning: it shouldn't be clickable). When the user enters the credentials of the form the button should be enabled to click for the user. So in this article, we are implementing a Text Watcher to t
3 min read
How to Implement Polling in Android?
Many times you may have seen on some apps like youtube, LinkedIn, etc. polling is done and users choose their options whatever they want to choose. Here we are going to implement polling in Android Studio. What we are going to build in this article? In this article, we will ask the user a question a
4 min read
How to Implement Preferences Settings Screen in Android?
In many apps, we have seen the Settings screen which is most common in most of the apps. This settings screen is used to manage the preferences of the users. For creating this settings screen android provides a feature to make a settings preferences screen. In this article, we will take a look at im
7 min read
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 Notification Counter in Android?
Notification Counter basically counts the notifications that you got through an application and shows on the top of your application icon so that you get to know you get new messages or any new update without opening your application or specific feature like the message button in Instagram. Notifica
7 min read
How to Implement Swipe Down to Refresh in Android
Certain applications show real-time data to the users, such as stock prices, availability of a product on online stores, etc. Showing real-time data requires continuous syncing of the application, and could be possible by implementing a program such as a thread. A Thread could be initiated by the ap
3 min read
How to Implement Google Map Inside Fragment in Android?
In Android, the fragment is the part of 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. The UI fl
4 min read
How to Implement RecyclerView in a Fragment in Android?
In Android, a fragment is a modular section of a user interface that can be combined with other fragments to create a flexible and responsive application. Â A fragment represents a behavior or a portion of the user interface in an Activity, which can be reused in different activities or layouts. It h
12 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