1

I have a trouble with AlertDialog. If i will call dialog.show() after dialog.hide() it will not be shown, but if I call dialog.show() again, all ok. If i call dialog.show() twice in a row, dialog showing always.

And If replace hide() -> dismiss() it is ok allways. But in my case i need to use hide() to save the dialog.

SAMPLE

AlertDialog dialog;

@Override
protected void onCreate(@Nullable Bundle savedState) {
    super.onCreate(savedState);
    setContentView(R.layout.activity_auth);
    dialog = new AlertDialog.Builder(this)
        .setTitle("Title")
        .setMessage("Text")
        .setPositiveButton("Yes", (dialogInterface, which) -> onYesClicked())
        .create();
    Button login = findViewById(R.id.btn_login);
    login.setOnClickListener(v -> dialog.show());
}

private void onYesClicked() {
    dialog.hide();
}

EDITED: SOLUTION

private void onYesClicked() {
    new Handler().post(() -> dialog.hide());
}
punchman
  • 1,350
  • 1
  • 13
  • 23

5 Answers5

0

If you use, hide(), it may lead to Leaked Window error. Please have a look: Activity has leaked window that was originally added

Using dismiss() and save the message/title instead of the whole dialog.

Cao Minh Vu
  • 1,900
  • 1
  • 16
  • 21
0

If you want to use hide and show the dialog again, try this code:

dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface d) {
        dialog.show();
    }
});

when you call hide, and call show, the callback will be invoke.

yu wang
  • 283
  • 1
  • 6
  • Thanks, it really work. But it looks like to call `dialog.show()` twice in a row. But I found a better solution: `new Handler().post(() -> dialog.hide())` – punchman Mar 14 '18 at 03:24
0

try this to make the dialog pop up just once:

 if (dialog != null && dialog.getDialog() != null
                                && dialog.getDialog().isShowing()) {
                     //Leave Empty here or your way
}else{
 code to open a dialog
}
0

make some changes in onYesClicked() method used below code ..

private void onYesClicked() {
    new Handler().postDelayed(new Runnable() {

        // Showing message with a timer.
        @Override
        public void run() {
            dialog.hide();
        }
    }, 1000);

}
0

I solved this problem. Method hide() it is useless to call when a button (created by AlerdDialog.Builder) is clicked. Because system send MSG_DISMISS_DIALOG and automatically call dismiss() for this dialog:

SDK code:

        // Post a message so we dismiss after the above handlers are executed
        mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG, mDialogInterface)
                .sendToTarget();
punchman
  • 1,350
  • 1
  • 13
  • 23