Android Sharedpreferences Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of Android SharedPreferences

Understanding Android SharedPreferences

SharedPreferences in Android is a framework that allows you to save and retrieve key-value pairs of primitive data types. It's主要用于storing small amounts of data such as user preferences, settings, or session token, and can be accessed easily throughout an application. This mechanism is particularly useful for configuration settings that need to persist across different activities and sessions.

Basic Operations

  1. Saving Data:

    • To save data, you first need to get a SharedPreferences instance from the context. You can then use the edit() method to obtain a SharedPreferences.Editor object, which allows you to add or modify key-value pairs.
    • After modifying the data, you must call apply() or commit() to save the changes. While apply() is asynchronous and works well for most use cases, commit() is synchronous and returns a boolean indicating whether the write was successful.
    SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("username", "JohnDoe");
    editor.apply(); // or editor.commit();
    
  2. Retrieving Data:

    • To retrieve data, call getXXX() methods on the SharedPreferences object, providing the key and a default value in case the key doesn't exist.
    String username = sharedPreferences.getString("username", "defaultUsername");
    
  3. Editing Data:

    • You can modify existing entries or add new ones using the put methods on the Editor object.
    • Use remove() to delete a specific key-value pair, and clear() to remove all data from the preferences.
  4. Listening for Changes:

    • If you need to be notified of changes to SharedPreferences, you can register a listener using registerOnSharedPreferenceChangeListener(). This listener will be called whenever a preference is added, removed, or modified.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement Android SharedPreferences

Step 1: Set Up Your Android Project

First, create a new project in Android Studio.

  1. Open Android Studio and choose "Start a new Android Studio project."
  2. Choose "Empty Activity" and click "Next."
  3. Enter your project name, package name, and save location.
  4. Choose the language (Java/Kotlin) and select a minimum API level.
  5. Click "Finish" to create your project.

Step 2: Create Your Layout

Next, we'll design a simple layout to use in our example. Open res/layout/activity_main.xml and modify it as shown below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <EditText
        android:id="@+id/editTextName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name"
        android:inputType="textPersonName"/>

    <Button
        android:id="@+id/buttonSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"
        android:layout_below="@id/editTextName"
        android:layout_marginTop="16dp"/>

    <TextView
        android:id="@+id/textViewName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your Name:"
        android:layout_below="@id/buttonSave"
        android:layout_marginTop="16dp"/>

</RelativeLayout>

Step 3: Implement SharedPreferences in MainActivity

Now we will use SharedPreferences to save and retrieve the name from the EditText field.

Using Java:

package com.example.sharedpreferencesexample;

import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private EditText editTextName;
    private Button buttonSave;
    private TextView textViewName;

    // Name of the SharedPreferences file
    private static final String PREFS_NAME = "MyPrefsFile";

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

        editTextName = findViewById(R.id.editTextName);
        buttonSave = findViewById(R.id.buttonSave);
        textViewName = findViewById(R.id.textViewName);

        // Load the name from SharedPreferences
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String name = settings.getString("Name", "No name entered");
        textViewName.append(" " + name);

        buttonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editTextName.getText().toString();
                // Save the name to SharedPreferences
                SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("Name", name);
                editor.apply(); // or editor.commit();

                // Update the TextView
                textViewName.setText("Your Name: " + name);
            }
        });
    }
}

Using Kotlin:

package com.example.sharedpreferencesexample

import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    // Name of the SharedPreferences file
    private val PREFS_NAME = "MyPrefsFile"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Load the name from SharedPreferences
        val settings: SharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
        val name: String = settings.getString("Name", "No name entered") ?: "No name entered"
        textViewName.text = "Your Name: $name"

        buttonSave.setOnClickListener {
            val name: String = editTextName.text.toString()
            // Save the name to SharedPreferences
            val settings: SharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
            val editor: SharedPreferences.Editor = settings.edit()
            editor.putString("Name", name)
            editor.apply() // or editor.commit()

            // Update the TextView
            textViewName.text = "Your Name: $name"
        }
    }
}

Step 4: Run Your Application

Run the application on an emulator or a physical device.

  1. Connect your device or start an emulator.
  2. Click the "Run" button in Android Studio.
  3. Enter your name in the EditText field.
  4. Click the "Save" button.
  5. The name should be displayed in the TextView.
  6. Close the app and reopen it. The saved name should still be displayed, demonstrating that SharedPreferences has stored the data.

Summary

You have just implemented SharedPreferences in your Android application, allowing you to save and retrieve small amounts of data even when the app is closed and reopened. SharedPreferences is ideal for scenarios where you need to persist user preferences or settings. You can expand on this by saving other types of data, such as Boolean values, integers, floats, longs, or sets of strings.

Top 10 Interview Questions & Answers on Android SharedPreferences

1. What are SharedPreferences in Android?

Answer: SharedPreferences is an interface in Android used for storing and retrieving key-value pairs of primitive data types (like booleans, floats, integers, longs, and strings). It's a lightweight mechanism for saving small amounts of data in an XML file.

2. How do you create a SharedPreferences instance?

Answer: To create a SharedPreferences instance, you use either getSharedPreferences() or getPreferences() methods. For example:

  • getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE);
    • This creates a new SharedPreferences object pointing to the file named "PREFERENCE_NAME", with the mode set to private (accessible only by your app).
  • getPreferences(Context.MODE_PRIVATE);
    • Usually used in Activities when you want to create a default SharedPreferences file for the activity.

3. Can SharedPreferences be used for large data?

Answer: No, SharedPreferences are not suitable for storing large amounts of data. They are best used for storing small values like user settings, preferences, or simple application state information. For larger data, consider using a database (SQLite), file storage, or cloud storage.

4. How do you write data to SharedPreferences?

Answer: To write data to SharedPreferences, you must use a SharedPreferences.Editor object. Here's how you can do it:

SharedPreferences sharedPreferences = getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("key", "value");
editor.apply();
  • apply() is asynchronous and does not return a boolean. Prefer it for most use cases.
  • commit() is synchronous and returns a boolean indicating whether the write was successful. Use commit() if you need the result and are okay with blocking the UI thread.

5. How do you read data from SharedPreferences?

Answer: To read data from SharedPreferences, you use methods like getString(), getInt(), etc., providing the key and a default value if the key does not exist:

SharedPreferences sharedPreferences = getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE);
String value = sharedPreferences.getString("key", "default_value");
int intValue = sharedPreferences.getInt("int_key", 0);

6. How do you remove a key-value pair from SharedPreferences?

Answer: To remove a specific key-value pair from SharedPreferences, use the remove() method along with apply() or commit():

SharedPreferences sharedPreferences = getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("key");
editor.apply();

7. How do you clear all data from SharedPreferences?

Answer: To remove all data from a SharedPreferences, use the clear() method:

SharedPreferences sharedPreferences = getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();

8. Can SharedPreferences be accessed across different activities or components within the same app?

Answer: Yes, SharedPreferences can be accessed from any activity or component within the same app. However, they are scoped to the app's context, so you must specify the correct file name when retrieving the SharedPreferences instance.

9. Are SharedPreferences thread-safe?

Answer: While SharedPreferences is thread-safe in the context of reading and writing from multiple threads, it's important to handle concurrency carefully. For example, using apply() is generally safer for background threads as it operates asynchronously. However, commit() is synchronous and can block the calling thread, which could be risky on UI threads.

10. What is the recommended way to listen for changes in SharedPreferences?

Answer: To listen for changes in SharedPreferences, you can use a SharedPreferences.OnSharedPreferenceChangeListener. Here's an example of how to add a listener:

You May Like This Related .NET Topic

Login to post a comment.