Open In App

How to Save Switch Button State in Android?

Last Updated : 30 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 in android. 

What we are going to build in this article?

Here is a sample video of what we are going to build in this article. Note that we will be using Java language to make this project.

Step by Step Implementation

Step 1: Create a New Project

  • Open a new project.
  • We will be working on Empty Activity with language as Java. Leave all other options unchanged.
  • Name the application 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 on XML files

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:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:gravity="center"
    tools:context=".MainActivity">
 
    <androidx.appcompat.widget.SwitchCompat
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/switch_compat"
        android:text="Switch"
        android:textSize="25sp"/>
   
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">
       
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/bt_next"
            android:text="next"/>
       
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/bt_exit"
            android:text="Exit"/>
 
    </LinearLayout>
 
</LinearLayout>


Navigate to app > right-click < new < activity < empty activity and name it as MainActivity2. Use the following code in activity_main2.xml file-

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity2">
     
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Second Activity"
        android:textSize="30sp"/>
   
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt_back"
        android:text="back"/>
 
</LinearLayout>


Step 3. Working on Java files

Navigate to the MainActivity.java file and use the following code in it. Comments are added to the code to have a better understanding.

Java




package com.example.savestateofswitch;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
 
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends AppCompatActivity {
 
    // Initialize variable
    SwitchCompat switchCompat;
    Button btNext,btExit;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Assign variable
        switchCompat=findViewById(R.id.switch_compat);
        btNext=findViewById(R.id.bt_next);
        btExit=findViewById(R.id.bt_exit);
         
          // Save switch state in shared preferences
        SharedPreferences sharedPreferences=getSharedPreferences("save",MODE_PRIVATE);
        switchCompat.setChecked(sharedPreferences.getBoolean("value",true));
 
        switchCompat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (switchCompat.isChecked())
                {
                    // When switch checked
                    SharedPreferences.Editor editor=getSharedPreferences("save",MODE_PRIVATE).edit();
                    editor.putBoolean("value",true);
                    editor.apply();
                    switchCompat.setChecked(true);
                }
                else
                {
                    // When switch unchecked
                    SharedPreferences.Editor editor=getSharedPreferences("save",MODE_PRIVATE).edit();
                    editor.putBoolean("value",false);
                    editor.apply();
                    switchCompat.setChecked(false);
                }
            }
        });
 
        btNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Go to next activity
                Intent intent=new Intent(MainActivity.this,MainActivity2.class);
                startActivity(intent);
            }
        });
        btExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Close the app
                MainActivity.this.finishAffinity();
            }
        });
    }
}


Navigate to the MainActivity2.java file and use the following code in it. Comments are added to the code to have a better understanding.

Java




package com.example.savestateofswitch;
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity2 extends AppCompatActivity {
 
    // Initialize variable
    Button btBack;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
 
        // Assign variable
        btBack=findViewById(R.id.bt_back);
        btBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Go back
                Intent intent=new Intent(MainActivity2.this,MainActivity.class);
                startActivity(intent);
            }
        });
    }
}


Here is the final output of our application.

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads