Step #7: Deleting the Item

Deleting the ToDoModel seems fairly straightforward: call delete() on the ToDoRepository, supplying the model to be deleted. To help, add this delete() function to SingleModelMotor, which forwards the call to the repository:

  fun delete(model: ToDoModel) {
    repo.delete(model)
  }

However, there is one wrinkle: we do not want to go back to the DisplayFragment after deleting the item, as there is nothing to display. Instead, we should head back to the RosterListFragment.

To that end, add this navToList() function to EditFragment:

  private fun navToList() {
    hideKeyboard()
    findNavController().popBackStack(R.id.rosterListFragment, false)
  }

This hides the keyboard, then uses the NavController to pop the back stack. The default popBackStack() just pops one level off of the stack, akin to the user pressing BACK or the “up” arrow. In this case, we are telling the Navigation component:

Then, add this delete() function to EditFragment:

  private fun delete() {
    val model = motor.getModel()

    model?.let { motor.delete(it) }
    navToList()
  }

This deletes the current model in the binding, plus calls the new navToList() function.

Then, add another option to the when in onOptionsItemSelected() on EditFragment to call delete() if the user taps the “delete” app bar item:

  override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
      R.id.save -> {
        save()
        return true
      }
      R.id.delete -> {
        delete()
        return true
      }
    }

    return super.onOptionsItemSelected(item)
  }

If you run the sample app, add a new item, go back in to edit it, and click the delete app bar item, that newly-added item is deleted, and you return to an empty list.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.