SharedPreferences in Android — The Complete Guide
Everything you need to know about SharedPreferences in Android — when to use it, how to save, read, remove, and list all stored values. All examples in Kotlin.
This guide covers everything you need to know about SharedPreferences in Android — from understanding when to use it, to saving and retrieving data. All examples are in Kotlin.
What is SharedPreferences?
SharedPreferences is a key-value storage mechanism in Android. Data is stored as XML files in the app’s private directory at /data/data/<package_name>/shared_prefs/.
Use it for small, simple data — user settings, flags, tokens. For structured or relational data, use a database instead.
Creating SharedPreferences
There are two ways:
1. Default SharedPreferences (AndroidX)
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
This creates a file named <package_name>_preferences.xml. Requires the androidx.preference:preference-ktx dependency.
2. Named SharedPreferences
val prefs = context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE)
This creates a file named my_prefs.xml. Use this when you need multiple preference files or want a specific name.
Save Data
Use the edit() method to get a SharedPreferences.Editor, then call the appropriate put method:
val prefs = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE)
prefs.edit {
putString("username", "navkrishna")
putInt("login_count", 5)
putBoolean("is_logged_in", true)
}
The edit { } extension function (from androidx.core:core-ktx) automatically calls apply() when the block completes.
apply() vs commit()
| Method | Behavior |
|---|---|
apply() | Writes to disk asynchronously. Preferred in most cases. |
commit() | Writes to disk synchronously and returns true/false. Use only when you need to confirm the write succeeded. |
Read Data
val prefs = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE)
val username = prefs.getString("username", "") // default: ""
val loginCount = prefs.getInt("login_count", 0) // default: 0
val isLoggedIn = prefs.getBoolean("is_logged_in", false) // default: false
The second parameter is the default value returned when the key doesn’t exist.
Remove Data
Remove a single key:
prefs.edit {
remove("username")
}
Clear everything:
prefs.edit {
clear()
}
Get All Stored Values
To iterate through everything stored in SharedPreferences:
val allEntries = prefs.all
for ((key, value) in allEntries) {
Log.d("SharedPrefs", "$key = $value")
}
getAll() returns a Map<String, *> — the values can be String, Int, Boolean, Float, Long, or Set<String>.
Complete Example
Here’s a minimal example — an Activity that saves key-value pairs and displays them in a list. Tapping an item removes it.
class MainActivity : AppCompatActivity() {
private lateinit var prefs: SharedPreferences
private lateinit var adapter: ArrayAdapter<String>
private val entries = mutableListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
prefs = getSharedPreferences("demo_prefs", MODE_PRIVATE)
val etKey = findViewById<EditText>(R.id.etKey)
val etValue = findViewById<EditText>(R.id.etValue)
val btnSave = findViewById<Button>(R.id.btnSave)
val listView = findViewById<ListView>(R.id.listView)
adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, entries)
listView.adapter = adapter
loadEntries()
btnSave.setOnClickListener {
val key = etKey.text.toString().trim()
val value = etValue.text.toString().trim()
when {
key.isEmpty() -> etKey.error = "Enter key"
value.isEmpty() -> etValue.error = "Enter value"
else -> {
prefs.edit { putString(key, value) }
etKey.text.clear()
etValue.text.clear()
loadEntries()
}
}
}
listView.setOnItemClickListener { _, _, position, _ ->
val key = entries[position].substringBefore(" = ")
prefs.edit { remove(key) }
loadEntries()
}
}
private fun loadEntries() {
entries.clear()
for ((key, value) in prefs.all) {
entries.add("$key = $value")
}
adapter.notifyDataSetChanged()
}
}
Layout — activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/etKey"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Key"
android:inputType="text" />
<EditText
android:id="@+id/etValue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Value"
android:inputType="text" />
<Button
android:id="@+id/btnSave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save" />
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>