3
\$\begingroup\$

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?

asked May 11, 2012 at 9:02
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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.

answered May 13, 2012 at 20:14
\$\endgroup\$
1
  • \$\begingroup\$ Thanks for your response, yet I don't think we should discuss application design (as opposed to programming techniques) in the context of this question. This area is very controversial itself. \$\endgroup\$ Commented May 13, 2012 at 20:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.