Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss alert dialog builder from onpause

Tags:

android

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();
like image 795
Peter Avatar asked Jun 17 '13 01:06

Peter


People also ask

How do you dismiss a dialog box?

Using the task bar:Right-click the icon referring to the dialog box from the Windows taskbar and click “Close”.

How do I turn off AlertDialog?

AlertDialog generally consists of the main title, the message, and two buttons, technically termed as a positive button and a negative button. Both positive and negative buttons can be programmed to perform various actions. By default, the negative button lets close the AlertDialog without any additional lines of code.

Which method is used to hide the dialog?

hide() will just change the visibility status of the dialog but the object will be still there and can be shown again using show() method. dismiss() hides and also destroys the dialog.


1 Answers

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();
like image 100
Emanuel Moecklin Avatar answered Sep 28 '22 23:09

Emanuel Moecklin