0
0
Android Kotlinmobile~7 mins

SharedPreferences / DataStore in Android Kotlin

Choose your learning style9 modes available
Introduction

We use SharedPreferences or DataStore to save small pieces of information on your phone. This helps your app remember things like settings or user choices even after closing.

Saving user preferences like theme or language choice.
Remembering if the user is logged in or not.
Storing simple flags like if a tutorial was shown.
Keeping small counters or scores in a game.
Saving last opened screen or app state.
Syntax
Android Kotlin
val sharedPref = context.getSharedPreferences("prefs", Context.MODE_PRIVATE)

// To save data
sharedPref.edit().putString("key", "value").apply()

// To read data
val value = sharedPref.getString("key", "default")
SharedPreferences stores data as key-value pairs.
Use apply() to save changes asynchronously.
Examples
Save a boolean value to remember if user is logged in.
Android Kotlin
sharedPref.edit().putBoolean("isLoggedIn", true).apply()
Read the boolean value, default is false if not set.
Android Kotlin
val isLoggedIn = sharedPref.getBoolean("isLoggedIn", false)
Create a DataStore instance for storing preferences.
Android Kotlin
val dataStore = context.createDataStore(name = "settings")
Save a string value in DataStore using a key.
Android Kotlin
val EXAMPLE_KEY = preferencesKey<String>("example_key")

runBlocking {
  dataStore.edit { settings ->
    settings[EXAMPLE_KEY] = "Hello"
  }
}
Sample App

This simple app saves a username "Alice" in SharedPreferences and then reads it back. It prints a welcome message with the saved name.

Android Kotlin
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val sharedPref = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)

    // Save a value
    sharedPref.edit().putString("username", "Alice").apply()

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

    println("Welcome, $username")
  }
}
OutputSuccess
Important Notes

SharedPreferences is simple but not suited for large or complex data.

DataStore is a newer, safer alternative that uses Kotlin coroutines.

Always use keys carefully to avoid overwriting data.

Summary

SharedPreferences and DataStore save small data on device.

Use key-value pairs to store and retrieve data.

DataStore is recommended for modern apps using Kotlin.