Skip to content

Commit

Permalink
06_02e
Browse files Browse the repository at this point in the history
  • Loading branch information
davidgassner committed Jul 24, 2020
1 parent 671d6bd commit 495d588
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
10 changes: 10 additions & 0 deletions app/src/main/java/com/example/plainolnotes4/EditorFragment.kt
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.example.plainolnotes4

import android.app.Activity
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
Expand Down Expand Up @@ -63,6 +65,14 @@ class EditorFragment : Fragment() {
}

private fun saveAndReturn(): Boolean {

val imm = requireActivity()
.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(binding.root.windowToken, 0)

viewModel.currentNote.value?.text = binding.editor.text.toString()
viewModel.updateNote()

findNavController().navigateUp()
return true
}
Expand Down
22 changes: 22 additions & 0 deletions app/src/main/java/com/example/plainolnotes4/EditorViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,26 @@ class EditorViewModel(app: Application) : AndroidViewModel(app) {
}
}

fun updateNote() {
currentNote.value?.let {
it.text = it.text.trim()
if (it.id == NEW_NOTE_ID && it.text.isEmpty()) {
return
}

viewModelScope.launch {
withContext(Dispatchers.IO) {
if (it.text.isEmpty()) {
database?.noteDao()?.deleteNote(it)
} else {
database?.noteDao()?.insertNote(it)
}
}
}

}


}

}
3 changes: 3 additions & 0 deletions app/src/main/java/com/example/plainolnotes4/data/NoteDao.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,7 @@ interface NoteDao {
@Query("DELETE FROM notes")
fun deleteAll():Int

@Delete
fun deleteNote(note: NoteEntity)

}

0 comments on commit 495d588

Please sign in to comment.