← All courses

Storing Data: SharedPreferences & Room

🗓 May 31, 2026 ⏱ 1 min read

SharedPreferences (small key-value data)

Great for settings like “dark mode on” or the logged-in user id.

val prefs = getSharedPreferences("settings", MODE_PRIVATE)
prefs.edit().putBoolean("darkMode", true).apply()
val dark = prefs.getBoolean("darkMode", false)

Room (a real SQLite database)

Room is Google’s database library. You define an Entity (table), a DAO (queries) and a Database.

@Entity
data class Note(@PrimaryKey(autoGenerate = true) val id: Int = 0, val text: String)

@Dao
interface NoteDao {
    @Insert suspend fun add(note: Note)
    @Query("SELECT * FROM Note") suspend fun all(): List<Note>
}

@Database(entities = [Note::class], version = 1)
abstract class AppDb : RoomDatabase() {
    abstract fun noteDao(): NoteDao
}
Tip: Room methods marked suspend run off the main thread automatically — use them inside coroutines.