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: }
app/src/main/java/com/example/notes/EditNoteActivity.kt
Kotlin · Click a line number to comment · Tap a line to comment@@ -1,28 +1,35 @@
package com.example.notes
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
Added: import androidx.core.widget.doAfterTextChanged
import com.example.notes.databinding.ActivityEditNoteBinding
class EditNoteActivity : AppCompatActivity() {
private lateinit var binding: ActivityEditNoteBinding
private val repository by lazy { NoteRepository(this) }
Added: private val drafts by lazy { DraftStore(this) }
private var noteId: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityEditNoteBinding.inflate(layoutInflater)
setContentView(binding.root)
noteId = intent.getLongExtra("noteId", 0)
Removed: binding.body.setText(repository.load(noteId).body)
Added: binding.body.setText(drafts.load() ?: repository.load(noteId).body)
Added:
Added: binding.body.doAfterTextChanged { text ->
Added: drafts.save(text.toString())
Added: }
binding.save.setOnClickListener {
repository.save(noteId, binding.body.text.toString())
Added: drafts.clear()
finish()
}
binding.discard.setOnClickListener {
finish()
}
}
}
app/src/test/java/com/example/notes/DraftStoreTest.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 androidx.test.core.app.ApplicationProvider
Added: import org.junit.Assert.assertEquals
Added: import org.junit.Test
Added: import org.junit.runner.RunWith
Added: import org.robolectric.RobolectricTestRunner
Added:
Added: @RunWith(RobolectricTestRunner::class)
Added: class DraftStoreTest {
Added: @Test
Added: fun savedDraftLoadsBack() {
Added: val store = DraftStore(ApplicationProvider.getApplicationContext())
Added: store.save("Buy milk")
Added: assertEquals("Buy milk", store.load())
Added: }
Added: }