Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent dialog to be opened multiple times when resuming activity

In my Android application, in order to ask the user if he/she wants to resume a current game, I display a dialog saying "Do you want to resume current game? Yes - No" on the main game activity.

The thing is that if I resume various times this activity without answering the dialog, then I get several dialogs, on top of each other, which is obviously not my goal.

I could easily avoid this behavior using a Boolean var, but I was wondering if the Dialog class had a kind of option preventing to be duplicated or something of the kind.

like image 377
thomaus Avatar asked Nov 15 '11 10:11

thomaus


4 Answers

You can use singleton pattern, could be roughly like this:

Dialog myDialog = null;


public void showDialog() {
    if(myDialog == null) {
        /* show your dialog here... */
        myDialog = ...
    }
}


public void hideDialog() {
    if(myDialog != null) {
        /* hide your dialog here... */
        myDialog = null;
    }
}
like image 83
Caner Avatar answered Nov 09 '22 20:11

Caner


private Dialog mDialog;

private void showDialog(String title, String message) {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(message);

    // Dismiss any old dialog.
    if (mDialog != null) {
        mDialog.dismiss();
    }

    // Show the new dialog.
    mDialog = dialogBuilder.show();
}
like image 20
Mathias Jeppsson Avatar answered Nov 09 '22 20:11

Mathias Jeppsson


Rather then doing hacks or using booleans you can use the method given by google itself

public boolean isShowing ()

it Returns a boolean value Whether the dialog is currently showing.

like image 4
Rahul Aswani Avatar answered Nov 09 '22 20:11

Rahul Aswani


I also encountered such a problem when I tried to override the onDismiss() method without super.onDismiss(dialog);

It turns out I deleted super.onDismiss(dialog) and because of this, the dialogs were duplicated

Back added, the error disappeared.

I hope someone will help

like image 2
DevOma Avatar answered Nov 09 '22 19:11

DevOma