Step #3: Replacing the Item
Now that we have the app bar item, we can get control when it is clicked and update our repository with a revised ToDoModel
.
Create this save()
function on EditFragment
:
private fun save() {
binding?.apply {
val model = motor.getModel()
val edited = model?.copy(
description = desc.text.toString(),
isCompleted = isCompleted.isChecked,
notes = notes.text.toString()
) ?: ToDoModel(
description = desc.text.toString(),
isCompleted = isCompleted.isChecked,
notes = notes.text.toString()
)
edited.let { motor.save(it) }
}
}
Here we:
- Retrieve our current
ToDoModel
from the viewmodel - Use the
copy()
function on ourdata
class to create a revised instance ofToDoModel
with the data from the form - If, inexplicably,
getModel()
returnednull
, create a newToDoModel
with the data from the form - Tell the
SingleModelMotor
to replace the existingToDoModel
for this ID with this new or revised model
Then, arrange to call this save()
method when the user clicks on the “save” app bar item, by adding this onOptionsItemSelected()
function to EditFragment
:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.save -> {
save()
return true
}
}
return super.onOptionsItemSelected(item)
}
If you run the app, select some to-do item, make some change to that item, then click that app bar item… nothing seems to happen. But, if you then press BACK to return to the DisplayFragment
, then BACK again to return to the list, you will see that… the list appears to be unchanged.
These are problems. And, we will fix them in the next couple of steps.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.