Adding a Delete confirmation prompt

It's best practice for apps to provide a confirmation before performing any type of destructive update, particularly if it cannot be undone. As such we need to provide a confirmation for the Delete action. Fortunately, Android makes this relatively easy with the AlertDialog and AlertDialog.Builder classes. The AlertDialog class allows you to display a modal confirmation dialog. The AlertDialog.Builder class is an embedded class that helps to construct an instance of an AlertDialog method; you can think of it as a factory class. The steps are as follows:

  1. Create an instance of AlertDialog.Builder.
  2. Set various properties on the builder instance, such as the message, the button text, the calling of event handlers when a button is clicked, and so on.
  3. Call Show() on the instance of AlertDialog.Builder to create and display an instance of AlertDialog.

    In our case we want an AlertDialog class with a simple message and an OK and Cancel button. When Cancel is clicked on, we simply need to close the dialog and not do anything else. When OK is clicked on, we need to delete the POI and close the activity.

  4. Create an event handler that will be called when OK is clicked on and move the delete and finish logic into this new event handler. The following listing depicts these changes:
    protected void ConfirmDelete(object sender, EventArgs e)
    {
      POIData.Service.DeletePOI (_poi);
      Finish ();
    }
  5. Add the logic that constructs the AlertDialog class into the existing DeletePOI() method. The following listing depicts this logic:
    protected void DeletePOI()
    {
      AlertDialog.Builder alertConfirm =
               new AlertDialog.Builder(this);
      alertConfirm.SetCancelable(false);
      alertConfirm.SetPositiveButton("OK", ConfirmDelete);
      alertConfirm.SetNegativeButton("Cancel", delegate {});
      alertConfirm.SetMessage(String.Format("Are you sure youwant to delete {0}?", _poi.Name));
      alertConfirm.Show();
    }

The SetPositiveButton() and SetNegativeButton() methods allow button captions and event handlers to be specified. In the case of the NEGATIVE button Cancel, we provide an empty event handler because there is nothing to do; Android will take care of closing the dialog. AlertDialog also provides a NEUTRAL button.

Note

On devices prior to Honeycomb, the button order (left to right) was POSITIVE - NEUTRAL - NEGATIVE. On newer devices using the Holo theme, the button order (left to right) is NEGATIVE - NEUTRAL - POSITIVE.

Run POIApp and verify if the delete confirmation is working correctly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.147.215