Programming and Personal Development

Alerting the android user

Android’s AlertDialog, just like Toasts, is  way of communicating timely information to the user. However, unlike Toast messages, they interrupt the user’s current activity and expect them to explicitly acknowledge the message.

Android Dialog Lifecycle methods

Dialog is the parent class for all types of dialogs in android including the AlertDialog. Before looking at the specific usage of the AlertDialog lets know the common lifecycle methods available to all the dialogs.

Creation methods

The recommended place to create the dialog is  by overriding the activity’s onCreateDialog(int) method and supplying a integer that uniquely identifies the dialog. Upon doing so, android automatically manages the state of the dialog and associates it with the corresponding activity.  You can also create the dialog outside the OnCreateDialog() method and use the setOwnerActivity(Activity) to explicitly manage the association.

Display methods

When you want to show the dialog you can call the showDialog(int) method and pass its unique identifier as argument.  Android internally calls the onCreateDialog(), the first time showDialog() is called and instantiates the dialog.

Removal methods

There are two lifecycle methods available to dismiss the dialog from the UI
  • dismissDialog(int) : Dismisses the dialog identified by its argument. However, the previous state of the dialog is  still maintained. So any previous selections are retained.
  • removeDialog(int): Dismisses the dialog from the UI and completely removes any previous state and references.

Alert Dialog

AlertDialog is  an extension of the Dialog class and has the following features:

Demo output for android Alert Dialog

Alert Dialog Demo Activity

  • Title
  • Text Message
  • Dropdown list of selectable items and
  • Buttons for handling user response.  AlertDialogs can have up to 3 buttons.
A very simple way to construct the AlertDialog is to use the AlertDialog.Builder class. Its a typical builder pattern that provides methods for setting the various parameters and returns the Builder itself for easier chaining of methods.  Once the parameters are set, you can call the create() method on the builder to create a new instance of the AlertDialog.

Example

Lets look at the usage with an simple example.  The xml layout for the demo activity consists of 3 Button elements placed next to each other within a Linear Layout as shown.  Clicking each button, pops up a AlertDialog that demonstrates its various properties.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    <!-- 1. Button for standard alert dialog -->    <Button android:id="@+id/alert_simple"
            android:text="Simple Alert"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>
    <!--2. Button for AlertDialog with a single selection list-->    <Button android:id="@+id/alert_list"
            android:text="Alert list"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>
    <!--Alert Dialog with a multi-selection list. -->    <Button android:id="@+id/alert_multi_list"
            android:text="Alert Multi list"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>
</LinearLayout>

Lets now take a look at the java code.
  • First generate unique integers to represent the different dialogs and initialize a dummy list of Strings as input to the AlertDialogs having the drop-down list.
/* Set the Ids for identifying the types of  dialog */
private static final int DIALOG_SIMPLE = 1;
private static final int DIALOG_LIST = 2;
private static final int DIALOG_MULTI_LIST = 3;
 
/* Dummy Input list for list based dialogs */
private static final CharSequence[] itemList = {"Android", "Iphone", "Windows"};

  • Next we define a helper method that will raise a Toast message. This is the method that will be executed within the various callback methods that are available to the UI elements
/* Helper for creating the toast */
private void createToast(String message) {
   Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}

  • Define methods that create the AlertDialogs. In this example, we define 3 types of AlertDialogs. Lets look at them one by one.
    • Dialog with two buttons. Note the use of the AlertDialog.Builder class as mentioned before. Once we have the builder, we can set the desired message using the setMessage(), add buttons ( we can add upto 3 buttons)  and register callbacks using the OnClickListener interface. We can prevent the user from dismissing the dialog (using the “Esc” key or by clicking elsewhere) and force them to respond to Dialog by passing “false” as the argument to the setCancellable() method. Finally we call the create() on the builder to create a new instance of the AlertDialog. This is a simple way to create a android messagebox for  displaying some simple message or a confirm dialog with standard yes/no options.
/* Simple alert dialog with 2 buttons */
private Dialog createSimpleDialog() {
   AlertDialog.Builder builder = new AlertDialog.Builder(this);
   builder.setMessage("I am a simple Dialog with 2 buttons")
           .setCancelable(false)
                   /* Set the positive button ("YES"/ "OK")*/           .setPositiveButton("OK", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                 createToast("You clicked OK Button");
              }
           })
                   /* Set the negative button ("NO"/ "CANCEL")*/           .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                 createToast("You clicked the Cancel  Button");
              }
           });
   return builder.create();}

    • Dialog that allows selection of a single item from a list. We use the setSinglechoiceItems() method to set the list of items to display. The method takes in a item array, the default checked item (-1 indicates no selection) and a OnClickListener interface which provides a callback that gets executed when the user clicks a item on the list.
/* Uses the setSinglechoiceItems() to handle single selections */
private Dialog createListDialog() {
   AlertDialog.Builder builder = new AlertDialog.Builder(this);
   builder.setCancelable(true)
           .setSingleChoiceItems(itemList, -1, new DialogInterface.OnClickListener() {              @Override
              public void onClick(DialogInterface dialog, int which) {
                 createToast(itemList[which].toString());
 
              }
           });
   return builder.create();
}
    • Dialog that allows for multiple selections from a list.  Here we allow for multiple selections using the setMultiChoiceItems().  This method too takes in a input array of items, a array of booleans ( should be of the same size as the input array or null) that indicate the items that are selected by default and a OnMultiChoiceClickListener() interface.  Note that we have passed “true” to the setCancellable() method. This lets us dismiss the AlertDialog without responding to them.
/*  Uses the setMultipleChoiceItems() to handle multiple selections */
private Dialog createMultiListDialog() {
   AlertDialog.Builder builder = new AlertDialog.Builder(this);
   builder.setCancelable(true)           .setMultiChoiceItems(itemList, null, new DialogInterface.OnMultiChoiceClickListener() {              @Override
              public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                 CharSequence item = itemList[which];
                 String message = itemList[which] + " is " + (isChecked ? "selected" : "deselected");
                 createToast(message);
              }
           });
 
   return builder.create();
}

  • Now that we have defined the dialog creation methods, lets override the onCreateDialog(int) within the activity.  We match the unique id representing the Dialog with a switch statement to direct the control to the corresponding Dialog creation method.
/* onCreateDialog() gets called the first time the dialog needs to be created */
@Override
protected Dialog onCreateDialog(int id) {
   Dialog dialog = null;
   switch (id) {
      case DIALOG_SIMPLE: {
         dialog = createSimpleDialog();
         break;
      }
      case DIALOG_LIST: {
         dialog = createListDialog();
         break;
      }
      case DIALOG_MULTI_LIST: {
         dialog = createMultiListDialog();
         break;
      }
      default:
         dialog = super.onCreateDialog(id);
   }
   return dialog;
}

  • Finally, we call the showDialog() method within the OnClickListeners of  the Button elements in our Demo activity’s onCreate() method and pass in the unique  integers that identify the 3 different AlertDialogs.  Android automatically calls the onCreateDialog() method the first time showDialog() is called.  Note that, we also call the removeDialog() method within the listener interface of the Single Selection AlertDialog. This ensures that any previous selections are cleared. This is not the case with the other 2 AlertDialogs where we the previous state is managed and retained by Android.
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.alert_demo);
   /* 1. Standard alert Dialog with 2 buttons*/   Button simpleAlert = (Button) findViewById(R.id.alert_simple);
   simpleAlert.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         showDialog(DIALOG_SIMPLE);      }
   });
 
   /* 2. Dialog with a list of items. Single selection only */   Button listAlert = (Button) findViewById(R.id.alert_list);
   listAlert.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         removeDialog(DIALOG_LIST);         showDialog(DIALOG_LIST);      }
   });
 
   /* 3. Dialog with a list of items. Multiple selections */   Button multiListAlert = (Button) findViewById(R.id.alert_multi_list);
   multiListAlert.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         showDialog(DIALOG_MULTI_LIST);      }
   });
}

Web Analytics