Devesh Rx Logo
Devesh Rx Blog

How to Use SharedPreferences in Android (Kotlin & Compose)

June 10, 2026

How to Use SharedPreferences in Android (Kotlin & Compose)

Android SharedPreferences Tutorial: How to Save Key-Value Data in Kotlin

If you are building an Android app, you will inevitably need to save small pieces of data—like user settings, login sessions, or app preferences. This is where Android SharedPreferences comes in.

In this complete tutorial, we will explore how to use SharedPreferences in Android to store simple key-value data persistently. Whether you are using traditional Views or modern Jetpack Compose, you will learn how to initialize, write, read, and delete data efficiently. We will also dive into advanced best practices, including building a thread-safe Singleton Manager for large-scale applications.

Let’s dive into how you can implement Android’s most popular lightweight storage solution.

What is SharedPreferences in Android?

In simple terms, SharedPreferences is an Android API that allows you to store and retrieve small amounts of primitive data as key-value pairs. The data is saved persistently, meaning it survives even if the user closes the app or restarts their device.

Under the hood, Android takes your key-value pairs and saves them into a simple XML file hidden inside your app’s private storage directory.

SharedPreferences vs. Room Database

A common question developers ask is: When should I use SharedPreferences instead of a Room Database?

  • Room Database: Best for complex, structured data (like a list of users, offline caching, or relational tables).
  • SharedPreferences: Best for incredibly simple data. If you just need to save a boolean indicating that the user has enabled “Dark Mode” or “Auto-Sync,” a Room DB is overkill. Use SharedPreferences.

How to Implement SharedPreferences in Kotlin

Let’s walk through the exact code needed to make this work in Android Studio.

1. Initialization

To use SharedPreferences, you must first create or access a preference file. You can create multiple files by giving them unique names.

// Retrieve SharedPreferences inside an Activity or Fragment
val sharedPref = context.getSharedPreferences("my_user_data", Context.MODE_PRIVATE)
  • "my_user_data": The custom name of the XML file generated on the device.
  • Context.MODE_PRIVATE: This crucial security flag ensures that only your application can read or write to this specific file.

2. Writing and Saving Data

To modify preferences, you need to use a SharedPreferences.Editor. In modern Android development, the best practice is to use the androidx.core.content.edit KTX extension, which provides a much cleaner syntax.

// Using the Kotlin KTX extension (Recommended)
sharedPref.edit {
    putString("user_id", "ID_123456")
    putInt("user_age", 25)
    putBoolean("auto_sync", true)
}

Pro Tip: The KTX .edit {} block automatically calls apply() for you in the background. apply() saves the data asynchronously, which is safer for your UI thread compared to the older, synchronous commit() method.

3. Reading Data

Reading data is straightforward. However, you must always provide a default value. This acts as a fallback just in case the key you are looking for doesn’t exist yet.

val userId = sharedPref.getString("user_id", "Not Found")
val userAge = sharedPref.getInt("user_age", 0)
val isSyncEnabled = sharedPref.getBoolean("auto_sync", false)

4. Deleting Data

If a user logs out, you may want to erase their specific session ID, or clear the entire file entirely.

sharedPref.edit {
    remove("user_id") // Deletes a single specific key
    // clear()        // Uncomment to wipe the entire file completely
}

Where is the SharedPreferences File Stored in Android?

Once you save your data, you might be wondering where it actually goes. You can inspect the saved XML file directly inside Android Studio.

  1. Open Android Studio and run your app on an emulator or physical device.
  2. Navigate to the bottom right and open the Device Explorer (or View > Tool Windows > Device File Explorer).
  3. Follow this folder path: data -> data -> <your.app.package.name> -> shared_prefs
  4. Here, you will find your my_user_data.xml file. Double-click to open it!

It will look something like this:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="user_id">ID_123456</string>
    <int name="user_age" value="25" />
</map>

Using SharedPreferences with Jetpack Compose

If you are building modern UIs with Jetpack Compose, integrating SharedPreferences requires working with LocalContext and Compose state. Here is a simple example of saving a user input directly from a Composable:

@Composable
fun SharedPreferencesDemo() {
    val context = LocalContext.current
    var inputKey by remember { mutableStateOf("user_name") }
    var inputValue by remember { mutableStateOf("") }

    Column(modifier = Modifier.padding(16.dp)) {
        TextField(
            value = inputValue,
            onValueChange = { inputValue = it },
            label = { Text("Enter User Name") }
        )

        Button(
            onClick = {
                val pref = context.getSharedPreferences("my_user_data", Context.MODE_PRIVATE)
                pref.edit {
                    putString(inputKey, inputValue)
                }
                Toast.makeText(context, "Data Saved Successfully!", Toast.LENGTH_SHORT).show()
            },
            modifier = Modifier.padding(top = 8.dp)
        ) {
            Text("Save to SharedPreferences")
        }
    }
}

🌟 Best Practice: Creating a SharedPreferences Singleton Manager

(Advanced Architecture Tip)

If you are working on a large-scale Android project, repeatedly calling getSharedPreferences() in every Activity, Fragment, or ViewModel is a bad practice. It leads to code duplication, increases the risk of typos in your keys, and can slow down performance by creating duplicate instances.

The industry standard is to wrap your SharedPreferences logic inside a Thread-Safe Singleton Class. This centralizes your data management and uses the applicationContext to prevent memory leaks.

package com.yourdomain.app.storage

import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit

class SharedPreferencesManager private constructor(context: Context) {

    private val sharedPreferences: SharedPreferences =
        context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)

    companion object {
        private const val PREF_NAME = "my_user_data"

        @Volatile
        private var INSTANCE: SharedPreferencesManager? = null

        // Thread-safe Singleton implementation
        fun getInstance(context: Context): SharedPreferencesManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: SharedPreferencesManager(context.applicationContext).also {
                    INSTANCE = it
                }
            }
        }
    }

    // --- Simplified Save Methods ---
    fun saveString(key: String, value: String) {
        sharedPreferences.edit { putString(key, value) }
    }

    fun saveBoolean(key: String, value: Boolean) {
        sharedPreferences.edit { putBoolean(key, value) }
    }

    // --- Simplified Read Methods ---
    fun getString(key: String, defaultValue: String? = null): String? {
        return sharedPreferences.getString(key, defaultValue)
    }

    fun getBoolean(key: String, defaultValue: Boolean = false): Boolean {
        return sharedPreferences.getBoolean(key, defaultValue)
    }

    // --- Utility Methods ---
    fun delete(key: String) = sharedPreferences.edit { remove(key) }
    fun clearAll() = sharedPreferences.edit { clear() }
}

Why is this a Game-Changer? Instead of writing 4 lines of context and editor code every time you want to save data, you can now save a value anywhere in your app with a single, highly-readable line of code: SharedPreferencesManager.getInstance(context).saveString("user_id", "ID_123456")

(Note: If you are storing sensitive data like passwords or authentication tokens, always use EncryptedSharedPreferences from the AndroidX Security library instead of the standard API).


Frequently Asked Questions

What data types can SharedPreferences store?

SharedPreferences can store primitive data types: String, Int, Float, Long, Boolean, and StringSet. It cannot store complex objects natively (unless you serialize them into JSON strings using a library like Gson or Moshi).

What is the difference between apply() and commit()?

apply() saves the data to memory immediately and writes it to the disk asynchronously in the background. It is highly recommended. commit() writes to the disk synchronously and returns a boolean indicating success, but it can block the main UI thread and cause app stuttering.

Is SharedPreferences being deprecated?

No, but Google has introduced Jetpack DataStore as the modern, Coroutine-based successor to SharedPreferences. DataStore is type-safe and fully asynchronous. However, SharedPreferences is still fully supported, easier for beginners, and wildly prevalent in legacy codebases.

How do I delete a SharedPreferences file completely?

You can clear all keys inside the file using sharedPreferences.edit().clear().apply(). To physically delete the XML file from the device storage, you must use context.deleteSharedPreferences("my_user_data").


📌 Full Course Playlist https://www.youtube.com/playlist?list=PLO1OrQEU0vHNmD9Xqzs-qXwzzwrDvdhVu

#Tutorial
0 Introduction
1 Setting up Android Studio IDE
2 Mastering Android Studio: Navigating the IDE & Project Structure
3 Android Activity & Lifecycle Explained
4 Android Services: Background, Foreground, and Bound Services Explained
5 Android Broadcast Receivers: The Complete Guide to Listening and Sending Events
6 Android Content Provider API Tutorial: Access User Data Safely (Kotlin)
7 How to Build UI with Jetpack Compose: A Beginner’s Guide
8 Android Runtime Permissions in Kotlin and Jetpack Compose: Step-by-Step Guide
9 Android Intents Guide: Master Screen Navigation and Data Sharing
10 Android Room Database: Complete CRUD Tutorial with Kotlin
11 Android Internal Storage: File I/O Tutorial
12 Android MediaStore API Tutorial: How to Save and Read Files
13 Master Storage Access Framework in Jetpack Compose
14 How to Create Android Notifications with Jetpack Compose & Kotlin
15 How to Use SharedPreferences in Android (Kotlin & Compose)

~ ~ THANK YOU FOR READING ~ ~

Share: