Paramclasses Academy - Blog

Tutorials Details

←
Post 21 of 40
→

What is SharedPreferences in Android – Save and Retrieve Small App Settings with Java ?

What is SharedPreferences in Android – Save and Retrieve Small App Settings with Java ?

November 3, 2026

1. Introduction

Every Android application needs to store some information.

For example:

  • A user's name.

  • A user's selected theme.

  • Login screen preferences.

  • Notification settings.

  • Language preferences.

  • Small application settings.

But how can an Android application remember this information after the user closes the app?

Android provides an API called SharedPreferences to store small amounts of data in key-value pairs.

In this tutorial, we will learn how to save, retrieve, update and delete data using SharedPreferences in Android Studio with Java.

We will also build a practical application that saves a user's name and city.

2. What Is SharedPreferences in Android?

SharedPreferences is an Android API used to store small amounts of data in key-value pairs.

A key is the name used to identify a value.

For example:

Key: username
Value: Rahul

Key: city
Value: Raipur

Key: isLoggedIn
Value: true

The application can retrieve these values whenever they are needed.

Why Do We Use SharedPreferences?

SharedPreferences is useful when an application needs to remember small pieces of information.

Examples:

  • Remembering a user's selected theme.

  • Saving a language preference.

  • Storing a welcome screen setting.

  • Remembering whether a tutorial has already been completed.

  • Saving simple user preferences.

Important Features

  • Stores data as key-value pairs.

  • Saves data persistently.

  • Supports common data types.

  • Allows data to be updated.

  • Allows individual keys or all preferences to be removed.

  • Data is private to the application when using MODE_PRIVATE.

Important: SharedPreferences is suitable for small preference data, not large collections or relational records. For new projects, Android also recommends considering Jetpack DataStore for small preference storage and Room for structured database data.

3. Understanding Key-Value Pairs

SharedPreferences stores information using a key and its corresponding value.

For example:

username = "Rahul"
age = 22
isLoggedIn = true

Here:

  • username is the key.

  • "Rahul" is the value.

  • age is the key.

  • 22 is the value.

  • isLoggedIn is the key.

  • true is the value.

To retrieve a value, we use its key.

For example:

String name = sharedPreferences.getString(
    "username",
    ""
);

This retrieves the value stored under the username key.

The second argument is the default value. If the key does not exist, the application returns an empty string.

4. How to Create SharedPreferences in Java

First, we need to get a SharedPreferences object.

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

Understanding the code:

  • getSharedPreferences() opens or creates a preferences file.

  • "MyPreferences" is the file name.

  • MODE_PRIVATE makes the file accessible only to this application under normal Android app sandbox rules.

If the preferences file does not exist, Android creates it when changes are saved.

5. How to Save Data Using SharedPreferences

To save information, we need a SharedPreferences.Editor.

Example:

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

SharedPreferences.Editor editor =
        sharedPreferences.edit();

editor.putString("username", "Rahul");

editor.apply();

Understanding the code:

  • edit() creates an Editor.

  • putString() stores a String value.

  • "username" is the key.

  • "Rahul" is the value.

  • apply() applies the changes and saves them asynchronously to disk.

Common Data Types Supported

SharedPreferences supports these common data types:

1. String

editor.putString("username", "Rahul");

2. Integer

editor.putInt("age", 22);

3. Boolean

editor.putBoolean("isLoggedIn", true);

4. Float

editor.putFloat("price", 99.50f);

5. Long

editor.putLong("userId", 123456L);

You can save multiple values using the same Editor before calling apply().

6. How to Retrieve Data Using SharedPreferences

To retrieve saved data, use the appropriate getter method.

Example:

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

String name = sharedPreferences.getString(
        "username",
        "Guest"
);

If the username key exists, the application returns its saved value.

If it does not exist, the application returns "Guest".

Retrieving Different Data Types

Retrieve String:

String name = sharedPreferences.getString(
    "username",
    "Guest"
);

Retrieve Integer:

int age = sharedPreferences.getInt(
    "age",
    0
);

Retrieve Boolean:

boolean isLoggedIn = sharedPreferences.getBoolean(
    "isLoggedIn",
    false
);

Retrieve Float:

float price = sharedPreferences.getFloat(
    "price",
    0.0f
);

Retrieve Long:

long userId = sharedPreferences.getLong(
    "userId",
    0L
);

Always use a getter that matches the type originally stored under that key.

7. Difference Between apply() and commit()

SharedPreferences provides two methods for saving changes.

apply()

editor.apply();
  • Updates the in-memory preferences immediately.

  • Writes changes to disk asynchronously.

  • Does not return a success value.

  • Generally preferred for normal UI operations.

commit()

boolean result = editor.commit();
  • Writes changes to disk synchronously.

  • Returns true if the changes were successfully written.

  • Can block the current thread.

  • Avoid calling it on the main UI thread because it may slow down the application.

For most normal Android application settings, use apply().

8. How to Update Data in SharedPreferences

Updating data is simple.

Save a new value using the same key.

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

SharedPreferences.Editor editor =
        sharedPreferences.edit();

editor.putString("username", "Amit");

editor.apply();

If the username key already contains "Rahul", it will now contain "Amit".

The key remains the same; only its stored value changes.

9. How to Delete Data from SharedPreferences

SharedPreferences allows you to remove one key or clear all saved values.

Remove a Specific Key

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

SharedPreferences.Editor editor =
        sharedPreferences.edit();

editor.remove("username");

editor.apply();

This removes only the username value.

Clear All Preferences

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

SharedPreferences.Editor editor =
        sharedPreferences.edit();

editor.clear();

editor.apply();

This removes all values from that preferences file.

Use clear() carefully because it removes every stored preference in that file.

10. Practical Project: Create a Save User Details App

Now let's build a practical Android application.

Our application will allow users to:

  • Enter their name.

  • Enter their city.

  • Save the information.

  • Retrieve previously saved information.

  • Update saved information.

  • Clear saved information.

Step 1: Create a New Android Studio Project

  1. Open Android Studio.

  2. Select New Project.

  3. Choose Empty Views Activity.

  4. Set the project name to SharedPreferencesApp.

  5. Select Java as the programming language.

  6. Click Finish.

No additional library dependency is required for this basic SharedPreferences example.

Step 2: Design the XML Layout

Open:

app > res > layout > activity_main.xml

Replace the existing code with:

<?xml version="1.0" encoding="utf-8"?>

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="20dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SharedPreferences App"
            android:textSize="24sp"
            android:textStyle="bold"
            android:gravity="center"
            android:padding="15dp" />

        <EditText
            android:id="@+id/etName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Your Name"
            android:inputType="textPersonName" />

        <EditText
            android:id="@+id/etCity"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Your City"
            android:inputType="textCapWords" />

        <Button
            android:id="@+id/btnSave"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Save Data" />

        <Button
            android:id="@+id/btnLoad"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Load Data" />

        <Button
            android:id="@+id/btnClear"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Clear Data" />

        <TextView
            android:id="@+id/tvResult"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Saved Information Will Appear Here"
            android:textSize="18sp"
            android:padding="15dp"
            android:layout_marginTop="15dp" />

    </LinearLayout>

</ScrollView>

Understanding the XML:

  • ScrollView makes the screen scrollable.

  • etName collects the user's name.

  • etCity collects the user's city.

  • btnSave saves the information.

  • btnLoad retrieves saved information.

  • btnClear removes saved information.

  • tvResult displays the retrieved information.

Step 3: Write MainActivity.java Code

Open:

app > java > your package name > MainActivity.java

Write the following code:

package com.example.sharedpreferencesapp;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    EditText etName, etCity;

    Button btnSave, btnLoad, btnClear;

    TextView tvResult;

    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // Connect XML views with Java
        etName = findViewById(R.id.etName);
        etCity = findViewById(R.id.etCity);

        btnSave = findViewById(R.id.btnSave);
        btnLoad = findViewById(R.id.btnLoad);
        btnClear = findViewById(R.id.btnClear);

        tvResult = findViewById(R.id.tvResult);

        // Create or open SharedPreferences
        sharedPreferences = getSharedPreferences(
                "UserDetails",
                MODE_PRIVATE
        );

        // Save Button
        btnSave.setOnClickListener(v -> {

            String name = etName.getText().toString().trim();

            String city = etCity.getText().toString().trim();

            if (name.isEmpty()) {

                etName.setError("Please enter your name");
                etName.requestFocus();
                return;
            }

            if (city.isEmpty()) {

                etCity.setError("Please enter your city");
                etCity.requestFocus();
                return;
            }

            // Save data
            SharedPreferences.Editor editor =
                    sharedPreferences.edit();

            editor.putString("username", name);

            editor.putString("usercity", city);

            editor.apply();

            Toast.makeText(
                    MainActivity.this,
                    "Data Saved Successfully",
                    Toast.LENGTH_SHORT
            ).show();

        });

        // Load Button
        btnLoad.setOnClickListener(v -> {

            String name = sharedPreferences.getString(
                    "username",
                    ""
            );

            String city = sharedPreferences.getString(
                    "usercity",
                    ""
            );

            if (name.isEmpty() && city.isEmpty()) {

                tvResult.setText("No Saved Data Found");

            } else {

                tvResult.setText(
                        "Name: " + name +
                        "\nCity: " + city
                );

            }

        });

        // Clear Button
        btnClear.setOnClickListener(v -> {

            SharedPreferences.Editor editor =
                    sharedPreferences.edit();

            editor.clear();

            editor.apply();

            etName.setText("");
            etCity.setText("");

            tvResult.setText("All Data Cleared");

            Toast.makeText(
                    MainActivity.this,
                    "Data Cleared Successfully",
                    Toast.LENGTH_SHORT
            ).show();

        });

    }
}

Important: Replace the package declaration with your project's actual package name. Keep the package line generated by Android Studio if it is different.

Step 4: Understand the Java Code

1. Creating SharedPreferences

sharedPreferences = getSharedPreferences(
    "UserDetails",
    MODE_PRIVATE
);

This opens a preferences file named UserDetails.

If the file does not exist, Android creates it when data is saved.

2. Getting Input from EditText

String name = etName.getText().toString().trim();

This retrieves the user's name and removes extra spaces from the beginning and end.

3. Creating an Editor

SharedPreferences.Editor editor =
        sharedPreferences.edit();

The Editor allows us to add, update or remove preference values.

4. Saving User Name

editor.putString("username", name);

This saves the name using the key username.

5. Saving City

editor.putString("usercity", city);

This saves the city using the key usercity.

6. Applying Changes

editor.apply();

This applies the changes and saves them asynchronously.

7. Retrieving User Name

String name = sharedPreferences.getString(
    "username",
    ""
);

This retrieves the saved name. If no value exists, it returns an empty string.

8. Clearing Saved Information

editor.clear();
editor.apply();

This removes all saved values from the UserDetails preferences file.

11. Run and Test the Application

Now run the application on an emulator or a real Android phone.

Perform the following tests.

Test 1: Save User Information

  1. Enter your name.

  2. Enter your city.

  3. Click Save Data.

  4. You should see the message Data Saved Successfully.

Test 2: Retrieve Saved Information

  1. Click Load Data.

  2. Your saved name and city should appear in the TextView.

Test 3: Close and Reopen the App

  1. Save your information.

  2. Close the application.

  3. Open it again.

  4. Click Load Data.

Your previously saved information should still be available.

This demonstrates persistent local storage using SharedPreferences.

Test 4: Update Saved Information

  1. Enter a different name.

  2. Enter a different city.

  3. Click Save Data.

  4. Click Load Data.

The newly saved values should appear.

Test 5: Clear Saved Information

  1. Click Clear Data.

  2. Click Load Data.

  3. The application should display No Saved Data Found.

You have successfully implemented save, retrieve, update and delete operations using SharedPreferences.

12. Common Mistakes to Avoid

Mistake 1: Using Different Preference File Names

If you save data in UserDetails but try to retrieve it from another preferences file, the expected values will not be found.

Use the same file name:

getSharedPreferences("UserDetails", MODE_PRIVATE);

Mistake 2: Using Different Keys

If you save with:

editor.putString("username", name);

Retrieve using:

sharedPreferences.getString("username", "");

The key must match.

Mistake 3: Forgetting apply() or commit()

Changes made through an Editor must be applied or committed to be saved.

Mistake 4: Using the Wrong Getter Method

If you save a String with putString(), retrieve it with getString().

If you save an integer with putInt(), retrieve it with getInt().

Mistake 5: Expecting SharedPreferences to Store Large Data

SharedPreferences is intended for small key-value data. Use Room or another appropriate storage solution for structured records and larger datasets.

Mistake 6: Storing Sensitive Information

Do not store plain-text passwords, authentication secrets or other sensitive information in ordinary SharedPreferences.

13. Practice Tasks

Now try these tasks yourself:

  1. Add an EditText for the user's phone number.

  2. Save the phone number using putString().

  3. Retrieve the phone number using getString().

  4. Add a Boolean value named isLoggedIn.

  5. Save the login status using putBoolean().

  6. Retrieve the login status using getBoolean().

  7. Add a button that changes the saved username.

  8. Add a button that removes only the username using remove() without deleting the city.

Try completing these tasks without copying the code immediately.

14. Conclusion

In this tutorial, we learned how to store and retrieve small amounts of data using SharedPreferences in Android Studio with Java.

We covered:

  • What SharedPreferences is.

  • Understanding key-value pairs.

  • Creating a SharedPreferences object.

  • Saving data using SharedPreferences.Editor.

  • Retrieving different data types.

  • Understanding apply() and commit().

  • Updating saved values.

  • Removing individual keys.

  • Clearing all preferences.

  • Building a practical Save User Details App.

SharedPreferences is useful for storing simple application preferences and small settings that need to remain available after the application is closed.

←
Post 21 of 40
→