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();
Using the task bar:Right-click the icon referring to the dialog box from the Windows taskbar and click “Close”.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With