Android Development

Issue Tracker Android Updates Android Home Home Contact

Shared Preferences

Storing data in Android apps is essential for maintaining user preferences, saving app settings, caching lightweight data, or preserving small user-specific information. One of the simplest and most common solutions for this purpose is SharedPreferences.

  • SharedPreferences provides a convenient way to store and retrieve key-value pairs of primitive data types (Boolean, Float, Int, Long, String).
  • Data saved in SharedPreferences persists across app restarts and is stored locally until explicitly cleared or the app is uninstalled.
  • You can also save complex objects by serializing them into JSON strings using libraries like Gson or Moshi.
  • The data is stored as an XML file in: /data/data/YOUR_APP_PACKAGE/shared_prefs/.
  • Preferences are typically saved during lifecycle events like onPause() and restored in onCreate().

Storing Values

  • Create or access a SharedPreferences instance using:
    val prefs = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
  • Use edit() followed by methods like putString(), putInt(), etc., to store values.
  • Use apply() for asynchronous saving (recommended), or commit() for synchronous.

Example: Saving & Reading Data

val prefs = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)

// Store value
with(prefs.edit()) {
    putString("username", "abc")
    putInt("userAge", 25)
    apply()
}

// Retrieve values
val username = prefs.getString("username", "Guest")
val age = prefs.getInt("userAge", 0)
        

The second parameter in retrieval methods like getString() or getInt() is the default value, used when no entry is found for the given key.

When to Use SharedPreferences

Use SharedPreferences for storing simple configuration settings, flags, login status, or any other small persistent data. For structured, relational, or large data, use alternatives like Room or file storage.

Data Security

Data in SharedPreferences is stored in plain-text XML, making it vulnerable. For sensitive data like tokens or credentials:

  • Use EncryptedSharedPreferences (available in AndroidX Security library)
  • Or use the Android Keystore System for secure key management

Example secured storage code:
GitHub – SharedPrefs Security

Modern Alternative: Jetpack DataStore

Jetpack DataStore is a modern, asynchronous alternative to SharedPreferences. It uses Kotlin Flow and coroutines, and supports error handling and transactions. It is suitable for modern Android development with Jetpack components.
More info: Jetpack DataStore

Clear or Remove Preferences

// Remove a single value
prefs.edit().remove("username").apply()

// Clear all preferences
prefs.edit().clear().apply()
        

Context.MODE_PRIVATE keeps data private to your app. For cross-app communication, consider ContentProvider or FileProvider.