top of page
  • Writer's pictureMeghan Gill

SharedPreferences API Example in Android Studio

Updated: Aug 9, 2021

The #SharedPreferences API creates an XML file inside your app folder where preferences are saved until you uninstall the app.


SharedPreferences APIs are best used when there is a relatively small number of key-value pairs. It provides simple methods to store and retrieve values. You can retrieve the data even if the app has been killed.



SharedPreferences Usage


1. Save the user settings (settings page), i.e. with #selectioncontrols


2. To maintain if the user is logged in or not


3. Save the user details (userID, name) after login API. For further API calls we use the userID from shared preference.



SharedPreferences Example Tutorial with Switch Material


In this tutorial we will be using the SharedPreferences API to store a user's password privacy setting. We will enable "Show passwords" and use the SharedPreferences API to have the app remember that setting.




Step 1: This tutorial begins with the source code for the Android SwitchMaterial tutorial. Please find it below.



MainActivity.java

package io.meghandev.switchmaterialexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.CompoundButton;

import com.google.android.material.switchmaterial.SwitchMaterial;

public class MainActivity extends AppCompatActivity {
    SwitchMaterial passwordSwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        passwordSwitch = findViewById(R.id.passwordSwitch);

        passwordSwitch.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(
            CompoundButton buttonView, boolean isChecked) {
                Log.d("TAG", "Password Switch is checked " 
                + isChecked);
            }
        });
    }
}


activity_main.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"
    android:layout_margin="24dp">

    <TextView
        android:id="@+id/tVPrivacy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Privacy"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>
        
    <TextView
        android:id="@+id/tVshowPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show passwords"
        app:layout_constraintTop_toBottomOf="@id/tVPrivacy"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginTop="32dp"/>

    <TextView
        android:id="@+id/tVpasswordDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display characters briefly as you type"
        app:layout_constraintTop_toBottomOf="@id/tVshowPassword"
        app:layout_constraintStart_toStartOf="parent"/>

    <com.google.android.material.switchmaterial.SwitchMaterial
        android:id="@+id/passwordSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
  app:layout_constraintBaseline_toBaselineOf="@id/tVshowPassword"/>


</androidx.constraintlayout.widget.ConstraintLayout>


Create a SharedPreferences Object


Step 2: In MainActivity.java create an object for SharedPreferences. For the method getSharedPreferences() the first parameter is the key or name and the second parameter is the MODE.


MODE_PRIVATE is the most common mode. It means no other app can access your XML file.


SharedPreferences sharedPreferences;
sharedPreferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);



Create an Editor Object and Save It


Step 3: Create an object for the editor to edit the XML file. We will create a method to hold it. Our method has a boolean as a parameter because a switch is an On/Off button.


The SharedPreference APIs are most commonly used with booleans, Strings and ints. Occasionally they are used with longs.


Name the method private void setPasswordSwitch(Boolean isEnabled).


private void setPasswordSwitch(Boolean isEnabled){ 
//use a Boolean as a parameter because a switch is either on or off
    SharedPreferences.Editor editor = sharedPreferences.edit();    
    //creates the editor
    editor.putBoolean("passwordSwitch", isEnabled); 
    //sets the passwordSwitch value to the key
    editor.apply(); 
    //writes the data to the XML file
}

Use the setPasswordSwitch() method inside the setOnCheckedChangeListener for our switch. Use the default isChecked variable as the setPasswordSwitch parameter.


passwordSwitch.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(
    CompoundButton buttonView, 
    boolean isChecked) 
    {
        Log.d("TAG", "Password Switch is checked " + isChecked);
        setPasswordSwitch(isChecked);
    }
});


Retrieve the Data


Step 4: Retrieve the data with the method getBoolean(). As parameters it accepts a key - use the key we created for putBoolean() - and a default value for the Boolean. This default is only used if a new value for the key has not been set.


sharedPreferences.getBoolean("passwordSwitch", false);

We will create a method to get the data but you only need the one line. The method is as follows:


private boolean getPasswordSwitch() {
    return sharedPreferences.getBoolean("passwordSwitch", false);
}


Update the UI Based on the Preference Value


Step 5: Create a variable to hold the value for the preference.


boolean isPasswordSwitchEnabled = getPasswordSwitch();


Use the variable isPasswordSwitchEnabled to update the UI. As we are working with a MaterialSwitch which is a #selectioncontrol, use the setChecked() method to update the UI.


passwordSwitch.setChecked(isPasswordSwitchEnabled);


Run the app and enabled the switch


Run the app again. Your preference will be remembered!




 

BONUS: How do we remove shared preference values?


During testing we may want to remove values. Also, a user may want to reset an app to its default settings.


To remove a specific key-value pair from SharedPreferences use the editor's remove() method and pass in the specific key, then apply() or commit() the changes.

To clear all key-value pairs from SharedPreferences use the editor's clear() method then apply() or commit() the changes.



 



Final Source Code MainActivity.java:

package io.meghandev.switchmaterialexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.CompoundButton;

import com.google.android.material.switchmaterial.SwitchMaterial;

public class MainActivity extends AppCompatActivity {
    SwitchMaterial passwordSwitch;
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        passwordSwitch = findViewById(R.id.passwordSwitch);
        sharedPreferences = getSharedPreferences(
            "MyPreferences", MODE_PRIVATE);
        sharedPreferences.getBoolean("passwordSwitch", false);
        boolean isPasswordSwitchEnabled = getPasswordSwitch();
        passwordSwitch.setChecked(isPasswordSwitchEnabled);

        passwordSwitch.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(
            CompoundButton buttonView, boolean isChecked) 
            {
                Log.d("TAG", 
                "Password Switch is checked " 
                + isChecked);
                setPasswordSwitch(isChecked);
            }
        });
    }

    private void setPasswordSwitch(Boolean isEnabled){ 
           //we need a Boolean because a switch is either on or off
        SharedPreferences.Editor editor = sharedPreferences.edit();         
            //create the editor
        editor.putBoolean("passwordSwitch", isEnabled); 
            //sets the passwordSwitch value
        editor.apply(); //writes the data to the XML file
    }

    private boolean getPasswordSwitch() {
        return sharedPreferences.getBoolean(
        "passwordSwitch", 
        false
        );
    }
}


Final Source Code activity_main.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"
    android:layout_margin="24dp">

    <TextView
        android:id="@+id/tVPrivacy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Privacy"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>
        
    <TextView
        android:id="@+id/tVshowPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show passwords"
        app:layout_constraintTop_toBottomOf="@id/tVPrivacy"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginTop="32dp"/>

    <TextView
        android:id="@+id/tVpasswordDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display characters briefly as you type"
        app:layout_constraintTop_toBottomOf="@id/tVshowPassword"
        app:layout_constraintStart_toStartOf="parent"/>

    <com.google.android.material.switchmaterial.SwitchMaterial
        android:id="@+id/passwordSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
  app:layout_constraintBaseline_toBaselineOf="@id/tVshowPassword"/>


</androidx.constraintlayout.widget.ConstraintLayout>

471 views0 comments
bottom of page