SharedPreferences
Persist simple key-value data across app sessions using SharedPreferences. Learn to save, read, and remove preferences.
SharedPreferences is a free Android Academy lesson on CoddyKit — lesson 4 of 6. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, one of 6 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Persistent Storage Options
Android offers several ways to store data locally:
- SharedPreferences — simple key-value pairs (settings, tokens)
- Room — structured SQLite database (complex data)
- DataStore — modern async replacement for SharedPreferences
- Files — raw file I/O
SharedPreferences is perfect for simple settings and user preferences.
What Is SharedPreferences?
SharedPreferences stores data as key-value pairs in an XML file on the device. It supports:
- String
- Int / Long / Float
- Boolean
- Set<String>
Data persists across app restarts and survives configuration changes (rotation).
Getting a SharedPreferences Instance
Two ways to obtain a SharedPreferences object:
// 1. Named preferences (shared across activities)
val prefs = getSharedPreferences(
"MyAppPrefs", // file name
Context.MODE_PRIVATE // only your app can read it
)
// 2. Activity's default preferences
val prefs = getPreferences(Context.MODE_PRIVATE)Writing Data
Use an Editor to write values, then call apply():
val prefs = getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE)
prefs.edit()
.putString("username", "alice")
.putInt("login_count", 5)
.putBoolean("dark_mode", true)
.apply() // async, non-blocking — preferred over commit()
// Kotlin extension (cleaner syntax):
with(prefs.edit()) {
putString("username", "alice")
apply()
}Reading Data
Read values by key, providing a default if the key doesn't exist:
val prefs = getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE)
val username = prefs.getString("username", "Guest") // default: "Guest"
val count = prefs.getInt("login_count", 0) // default: 0
val darkMode = prefs.getBoolean("dark_mode", false) // default: false
println("Hello, $username! Logins: $count. Dark: $darkMode")Practical Example: Theme Toggle
Save and restore a dark mode setting:
class SettingsActivity : AppCompatActivity() {
private lateinit var binding: ActivitySettingsBinding
private lateinit var prefs: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySettingsBinding.inflate(layoutInflater)
setContentView(binding.root)
prefs = getSharedPreferences("settings", MODE_PRIVATE)
// Restore saved state
binding.switchDarkMode.isChecked = prefs.getBoolean("dark_mode", false)
binding.switchDarkMode.setOnCheckedChangeListener { _, isChecked ->
prefs.edit().putBoolean("dark_mode", isChecked).apply()
}
}
}Saving a Login Token
Store and check an auth token across app restarts:
// Save token after login
fun saveToken(token: String) {
getSharedPreferences("auth", MODE_PRIVATE)
.edit()
.putString("token", token)
.apply()
}
// Check if user is logged in
fun isLoggedIn(): Boolean {
val token = getSharedPreferences("auth", MODE_PRIVATE)
.getString("token", null)
return token != null
}
// Clear on logout
fun logout() {
getSharedPreferences("auth", MODE_PRIVATE)
.edit()
.remove("token")
.apply()
}Removing & Clearing Data
Remove specific keys or wipe all data:
.remove("key")— delete one entry.clear()— delete everything in the file
Always call .apply() (or .commit() if you need synchronous confirmation).
SharedPreferences vs DataStore
SharedPreferences works fine but has limitations:
- Synchronous reads can block the main thread
- No type safety
Jetpack DataStore is the modern replacement — fully async with Kotlin Flow and type safety. For new projects, prefer DataStore. SharedPreferences is still widely used and perfectly acceptable for small amounts of data.
Quick Check
Which method saves data to SharedPreferences asynchronously without blocking the UI thread?
Recap: SharedPreferences
You can now persist simple data across app launches:
- Get with
getSharedPreferences(name, MODE_PRIVATE) - Write:
.edit().putString(key, value).apply() - Read:
.getString(key, defaultValue) - Remove:
.edit().remove(key).apply() - Use
apply()(async) overcommit()(sync)
Next course: App Architecture — ViewModel, Room, and Coroutines.
Frequently asked questions
Is the “SharedPreferences” lesson free?
Yes — the full text of “SharedPreferences” is free to read here on the web, and the Android Academy course includes 6 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Android Academy course, upgrade to CoddyKit PRO.
What will I learn in “SharedPreferences”?
Persist simple key-value data across app sessions using SharedPreferences. Learn to save, read, and remove preferences. You practise Android Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Android Academy?
No prior experience is required. Android Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 6, so you can start here or from the beginning and move at your own pace.
How long does the “SharedPreferences” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Android Academy lesson?
Yes. Every Android Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.