Peter
Peter

Reputation: 5121

Dismiss alert dialog builder from onpause

I'm using the following code to display an alert dialog with two buttons. But if the dialog is not disissed when the activity is paused it throws an error. I know you can dismiss a dialog using .dismiss but this is an AlertDialog Builder not a Dialog. Any idea how to do this?

AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyActivity.this);

                // Setting Dialog Title
                alertDialog.setTitle("Title");

                // Setting Dialog Message
                alertDialog.setMessage("Message");

                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int which) {
                        //yes
                        dialog.cancel();

                    }
                });

                // Setting Negative "NO" Button
                alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        //no                
                    dialog.cancel();
                    }
                });

                // Showing Alert Message
                alertDialog.show();

Upvotes: 5

Views: 7549

Answers (1)

Emanuel Moecklin
Emanuel Moecklin

Reputation: 28856

You can get the AlertDialog when showing the dialog:

dialog = alertDialog.show(); // show and return the dialog

Then in the onPause you can dismiss the AlertDialog:

@Override
protected void onPause() {
    super.onPause();
    if (dialog != null) {
        dialog.dismiss();
    }
}

The dialog needs to be defined as instance variable for this to work:

private AlertDialog dialog; // instance variable

BTW the AlertDialog.Builder is a builder because you can use the builder pattern like so:

dialog = AlertDialog.Builder(MyActivity.this)
    .setTitle("Title");
    .setMessage("Message")
[...]
    .show();

Upvotes: 10

Related Questions