0
0
Android-kotlinHow-ToBeginner ยท 3 min read

How to Use Shared Preferences in Android for Simple Data Storage

In Android, use SharedPreferences to save small amounts of data as key-value pairs. Access it via getSharedPreferences(), then use edit() to save data and getXXX() methods to retrieve it.
๐Ÿ“

Syntax

Shared Preferences lets you store simple data as key-value pairs. You get a SharedPreferences object by calling getSharedPreferences(name, mode). To save data, use edit() to get an editor, then call putString(), putInt(), etc., and finally apply() or commit(). To read data, use getString(), getInt(), etc., with a default value.

kotlin
val sharedPref = getSharedPreferences("myPrefs", MODE_PRIVATE)
val editor = sharedPref.edit()
editor.putString("key", "value")
editor.apply()

val value = sharedPref.getString("key", "default")
๐Ÿ’ป

Example

This example shows how to save a username and then read it back when the app starts.

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

    val sharedPref = getSharedPreferences("userPrefs", MODE_PRIVATE)

    // Save username
    val editor = sharedPref.edit()
    editor.putString("username", "Alice")
    editor.apply()

    // Read username
    val username = sharedPref.getString("username", "Guest")

    Toast.makeText(this, "Welcome, $username", Toast.LENGTH_LONG).show()
  }
}
Output
A toast message appears: "Welcome, Alice"
โš ๏ธ

Common Pitfalls

  • Forgetting to call apply() or commit() after editing means changes won't save.
  • Using commit() blocks the main thread; prefer apply() for async saving.
  • Using different preference names or modes can cause data not to be found.
  • Trying to store large or complex data types is not supported; use a database instead.
kotlin
val editor = sharedPref.edit()
editor.putString("key", "value")
// Missing apply() or commit() here means data is not saved

// Correct way:
editor.putString("key", "value")
editor.apply()
๐Ÿ“Š

Quick Reference

MethodPurpose
getSharedPreferences(name, mode)Get preferences file by name
edit()Start editing preferences
putString(key, value)Save a string value
putInt(key, value)Save an integer value
apply()Save changes asynchronously
commit()Save changes synchronously
getString(key, default)Retrieve a string value
getInt(key, default)Retrieve an integer value
โœ…

Key Takeaways

Use SharedPreferences to store small key-value data persistently in Android.
Always call apply() or commit() after editing to save changes.
Prefer apply() over commit() to avoid blocking the main thread.
Use consistent preference names and modes to access the same data.
Avoid storing large or complex data; use a database for that.