Skip to content
Share
Explore

Shared Preferences in Android:

megaphone

The formula for shared preferences is : val sharedPreferences = getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE) You create a storage cabinet, "MyAppPrefs" in this case then you use putters and getters api methods to store and retrieve the values of keys

image.png

The SharedPreferences Formula:

1. Create/Open the Storage Cabinet:

val sharedPreferences = getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE)
"MyAppPrefs" = The name of your cabinet (becomes MyAppPrefs.xml file)
MODE_PRIVATE = Only your app can access this cabinet
This returns a SharedPreferences object that represents your storage cabinet

2. Get an Editor (to write/modify):


val editor = sharedPreferences.edit()
Think of this as getting a pen to write in your cabinet

3. Use Setter Methods (Putters) to Store:


editor.putString("username", "JohnDoe")
editor.putInt("highScore", 1500)
editor.putBoolean("soundEnabled", true)
editor.putFloat("volume", 0.8f)
editor.apply() // Don't forget to apply!

4. Use Getter Methods to Retrieve:


val username = sharedPreferences.getString("username", "defaultUser")
val highScore = sharedPreferences.getInt("highScore", 0)
val soundEnabled = sharedPreferences.getBoolean("soundEnabled", true)
val volume = sharedPreferences.getFloat("volume", 1.0f)
Second parameter is the default value if key doesn't exist

The Complete Pattern:


// 1. Create cabinet
val prefs = getSharedPreferences("MyStorage", Context.MODE_PRIVATE)

// 2. Writing (PUT)
prefs.edit().putString("key", "value").apply()

// 3. Reading (GET)
val value = prefs.getString("key", "default")
That's it! It really is that simple - create a named storage cabinet, then use put/get methods to store and retrieve your key-value pairs. The beauty is in its simplicity!

SharedPreferences is an Android Framework interface (not just a Kotlin object - it's part of Android's Java/Kotlin API) that mediates access to the file system, specifically storing key-value pairs in XML format.
The key-value pairs are stored as an XML file that looks like this:
xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="username">JohnDoe123</string>
<int name="score" value="100" />
<boolean name="soundEnabled" value="true" />
</map>
So the complete answer is:
SharedPreferences: An Android Framework interface (and its implementation)
Mediates access to: The app's private file system directory
Directory location: /data/data/[your.package.name]/shared_prefs/
Storage format: XML files (not a database, not JSON, not plain text - specifically XML)
The SharedPreferences object essentially provides a clean API to read/write XML files while maintaining an in-memory cache for performance.

The SharedPreferences Object is a persistent HashMap that automatically saves to and loads from an XML file!


SharedPreferences Architecture: The Complete Picture


The SharedPreferences Object

SharedPreferences is an Android Framework interface (not specifically Kotlin) that acts as a mediator between your app and the file system. Here's the precise architecture:

1. The Interface Hierarchy

kotlin
// SharedPreferences is actually an interface
public interface SharedPreferences {
// Methods for reading
String getString(String key, String defValue);
int getInt(String key, int defValue);
boolean getBoolean(String key, boolean defValue);
// ... etc
// Inner interface for editing
public interface Editor {
Editor putString(String key, String value);
Editor putInt(String key, int value);
// ... etc
void apply();
boolean commit();
}
}

2. The Actual Implementation

When you call:
kotlin
val sharedPreferences = getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE)
Android returns an instance of SharedPreferencesImpl (the concrete implementation) that:
Manages an in-memory cache (HashMap)
Handles file I/O operations
Ensures thread safety

The Storage Format: XML Files

The key-value pairs are stored in XML format on the file system. Here's exactly what it looks like:

File Location:

/data/data/com.example.sharedpreferencesdemo/shared_prefs/MyAppPrefs.xml

Actual File Contents:

xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="username">JohnDoe123</string>
<string name="email">john@example.com</string>
<int name="login_count" value="42" />
<boolean name="notifications_enabled" value="true" />
<float name="app_version" value="2.5" />
<long name="last_sync_timestamp" value="1625234567890" />
<set name="favorite_colors">
<string>red</string>
<string>blue</string>
<string>green</string>
</set>
</map>

The Complete Data Flow

Here's what happens when you interact with SharedPreferences:

Writing Data:


editor.putString("username", "JohnDoe123")
editor.apply()
Stage in Editor: The change is held in the Editor object
Update Memory: On apply(), updates the in-memory HashMap immediately
Queue Write: Schedules an asynchronous write to disk
Write XML: Background thread writes to the XML file

Reading Data:


val username = sharedPreferences.getString("username", "default")
Check Memory First: Looks in the HashMap (no file access!)
Return Value: Returns immediately from memory
Super Fast: No disk I/O needed for reads

Initial Load (App Startup):

First Access: When you first call getSharedPreferences()
Check File: Android checks if the XML file exists
Parse XML: If exists, parses the entire XML file
Load to Memory: Populates the HashMap with all key-value pairs
Ready: All subsequent operations use the in-memory cache

The XML Structure Explained

Let's break down each data type in the XML:
xml
<!-- String: stored as text content -->
<string name="key">value</string>

<!-- Integer: stored as attribute -->
<int name="key" value="123" />

<!-- Boolean: stored as attribute -->
<boolean name="key" value="true" />

<!-- Float: stored as attribute -->
<float name="key" value="3.14" />

<!-- Long: stored as attribute -->
<long name="key" value="9876543210" />

<!-- String Set: nested structure -->
<set name="key">
<string>item1</string>
<string>item2</string>
</set>

Why XML?

Android chose XML for SharedPreferences because:
Human Readable: Easy to debug and inspect
Structured: Naturally represents key-value pairs
Standard: Well-established format with built-in parsers
Type Preservation: Can distinguish between different data types
Lightweight: Perfect for small amounts of data

The SharedPreferences Lifecycle

App Start
getSharedPreferences() called
File exists? → Yes → Parse XML → Load to HashMap
↓ No
Create empty HashMap
All operations use HashMap (Memory)
apply() called → Async write to XML
App terminates → Data persists in XML
Next app start → Repeat cycle

Performance Characteristics

First Load: One-time XML parsing cost (milliseconds)
Reads: O(1) HashMap lookup - extremely fast
Writes: Immediate in memory, async to disk
Memory: Entire preferences loaded into RAM

Important Implementation Details

Thread Safety: SharedPreferencesImpl is thread-safe
Atomic Writes: Uses file renaming to ensure data integrity
Backup: Creates .bak file during writes for safety
Caching: Once loaded, never re-reads file during app lifetime

Summary

So yes, SharedPreferences is an Android Framework object (interface + implementation) that:
Mediates access to the file system
Stores data in XML format
Caches everything in memory for performance
Persists data in /data/data/[package]/shared_prefs/ directory
Manages thread safety and atomic writes
SharedPreferences is a persistent HashMap backed by an XML file!

info

Understanding SharedPreferences - How Android Stores Your App's Simple Data

Introduction: The Need for Data Persistence

Today we're going to explore one of the most fundamental concepts in Android development - data persistence.
Imagine you're using a weather app. You set your preferred temperature unit to Celsius, choose dark mode, and select your home city. Now, what happens when you close the app and open it again? Do you have to set all these preferences again? Of course not! The app remembers your choices. But how?
This is where SharedPreferences comes in - Android's simple, lightweight solution for storing small amounts of data.

What Are SharedPreferences?

SharedPreferences is Android's way of storing simple data in key-value pairs. Think of it like a dictionary or a phone book:
Key: The name you look up (like "John Smith")
Value: The information associated with that name (like "555-1234")
In our app:
Key: "username"
Value: "JohnDoe123"

What Can You Store?

SharedPreferences supports these data types:
String: Text values ("Hello World")
Int: Whole numbers (42)
Long: Large whole numbers
Float: Decimal numbers (3.14)
Boolean: True/False values
Set<String>: A collection of unique strings

The Engine Behind SharedPreferences: XML Files, Not SQLite!

Here's a common misconception I want to clear up: SharedPreferences does NOT use SQLite database. Instead, it uses something much simpler - XML files.

How It Actually Works:

Storage Location:
/data/data/[your.package.name]/shared_prefs/
For our app:
/data/data/com.example.sharedpreferencesdemo/shared_prefs/MyAppPrefs.xml
File Format: The data is stored as a simple XML file:
xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="username">JohnDoe123</string>
<int name="user_age" value="25" />
<boolean name="notifications_enabled" value="true" />
</map>
Why XML, not SQLite?
Simplicity: No need for database schemas or SQL queries
Speed: Faster for small amounts of data
Overhead: Much less overhead than maintaining a database
Purpose: Designed for preferences, not complex data

The Loading Process:

When your app starts:
Android loads the entire XML file into memory
Creates a HashMap (key-value pairs) in RAM
All reads happen from memory (very fast!)
Writes update both memory and the file

Breaking Down Our CRUD App

Let's walk through our lab app and see how each operation works:

1. Initial Setup - Creating the Storage Container

kotlin
// This line creates or opens our preferences file
sharedPreferences = getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE)

// This creates an editor to make changes
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.