PR Review Lab · Save Note Drafts as You Type

20:00left of 20:00

Save Note Drafts as You Type

If the app is killed while someone is editing a note, they lose what they typed. This saves the text to SharedPreferences as they type and restores it the next time the editor opens. Saving the note clears the draft. I tested it by typing, swiping the app away, and reopening it.

Aapp/src/main/java/com/example/notes/DraftStore.kt1 of 3

Files Changed

app/src/main/java/com/example/notes/

app/src/test/java/com/example/notes/

app/src/main/java/com/example/notes/DraftStore.kt

Kotlin · Click a line number to comment · Tap a line to comment
@@ -0,0 +1,17 @@
Added: package com.example.notes
Added:
Added: import android.content.Context
Added:
Added: class DraftStore(context: Context) {
Added: private val prefs = context.getSharedPreferences("drafts", Context.MODE_PRIVATE)
Added:
Added: fun save(text: String) {
Added: prefs.edit().putString("draft", text).commit()
Added: }
Added:
Added: fun load(): String? = prefs.getString("draft", null)
Added:
Added: fun clear() {
Added: prefs.edit().remove("draft").apply()
Added: }
Added: }