HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Efficient implemetation of AlertDialog callback in Android

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
androidimplemetationefficientcallbackalertdialog

Problem

One day I realised that my Android project utilizes AlertDialogs here and there in very ineffective way. The heavily duplicated portion of code looked like this (actually, copied and pasted from some documentation):

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you want to close application?")
  .setPositiveButton("Yes", new DialogInterface.OnClickListener()
  {
    public void onClick(DialogInterface dialog, int id)
    {
      dialog.dismiss();
      System.runFinalizersOnExit(true);
      System.exit(0);
    }
  })
  .setNegativeButton("No", new DialogInterface.OnClickListener()
  {
    public void onClick(DialogInterface dialog, int id)
    {
      dialog.dismiss();
    }
  });
builder.create().show();


Apparently, this code fragment should be transformed into a function accepting 2 parameters: a question to ask, and an action to perform.

After several iterations of code optimizations (each one of which seemed as the last and most minimal one), I came to the following class:

public abstract class DialogCallback implements DialogInterface.OnClickListener,Runnable
{
  DialogCallback(Context c, String q)
  {
    AlertDialog.Builder builder = new AlertDialog.Builder(c);
    builder.setMessage(q)
      .setPositiveButton("Yes", this)
      .setNegativeButton("No", this);
    builder.create().show();
  }

  public void onClick(DialogInterface dialog, int which)
  {
    dialog.dismiss();
    if(which == DialogInterface.BUTTON_POSITIVE) run();
  }
}


with the following usage:

new DialogCallback(context, "are you sure?")
{
  public void run()
  {
    // some action
  }
};


Is there a way of further optimization? What other methods for effective dialog callbacks can be used?

Solution

for a confirmation dialog use setCancelable(true) to make the user able to cancel the dialog using the back button. This is the native way and you don't have to implement anything.

Note: in Android you are not supposed to close the application. The operating system will close it when it feels like to do so.

Context

StackExchange Code Review Q#11677, answer score: 3

Revisions (0)

No revisions yet.