Android Academy · Lesson

SharedPreferences

Persist simple key-value data across app sessions using SharedPreferences. Learn to save, read, and remove preferences.

Lesson 4 of 611 steps

SharedPreferences is a free Android Academy lesson on CoddyKit. This is lesson 4 of 6. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, and your progress syncs across the web and the CoddyKit app. The Android Academy course includes 6 lessons in total.

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) over commit() (sync)

Next course: App Architecture — ViewModel, Room, and Coroutines.

Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
36
Lessons
152

Frequently Asked Questions

Is the “SharedPreferences” lesson free?

Yes — any 3 lessons of the Android Academy learning path, including “SharedPreferences”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Android Academy course includes 6 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 6.

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.

All lessons in this course

  1. Kotlin Collections
  2. RecyclerView Basics
  3. RecyclerView Click Events
  4. SharedPreferences
  5. DataStore Preferences
  6. Adapters & DiffUtil
← Back to Android Academy