Home » Java » AlertDialog is opened again

AlertDialog is opened again

Posted by: admin October 26, 2017 Leave a comment

Questions:

There is a fragment. When I press button on this fragment alert dialog is shown. This dialog is dissmissed after clicking on OK button. If I go to next fragment from current fragment and then come back – previous fragment is appeared with opened alert dialog. I use Cicerone for navigating. Maybe somebody faced with this problem?

// for navigating
router.navigateTo(screenKey);


// show dialog
AlertDialog alert = new AlertDialog.Builder(this)
        .setTitle(title)
        .setMessage(message)
        .setPositiveButton(R.string.ok, (dialog, which) -> dialog.dismiss())
        .setCancelable(true)
        .create();
alert.show();


// in my second fragment
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    showBackButton();
}


// in my main activity
@Override
public void showBackButton() {
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setHomeAsUpIndicator(Utils.getDrawable(this, R.drawable.ic_arrow_back_white_24dp));
    toolbar.setNavigationOnClickListener(v -> {
        onBackPressed();
    });
}

@Override
public void onBackPressed() {
    hideKeyboard();
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        hideDrawerLayout();
    } else {
        super.onBackPressed();
    }
}
Answers:
@Override
protected void onResume()
{
    super.onResume();
    dialog.close()
}

This will do the trick, in your parent activity where you are creating your dialog add this. Try to comment and uncomment super.onResume(); while testing.

Questions:
Answers:

What i got that You are navigating in first line and in next step you are showing the Dialog. These will execute one after another. I Hope you got my point . Do it as below :

 AlertDialog alert = new AlertDialog.Builder(this)
        .setTitle(title)
        .setMessage(message)
        .setPositiveButton(R.string.ok, (dialog, which) ->
                dialog.dismiss()// Optinal
                router.navigateTo(screenKey);
        )
        .setCancelable(true)
        .create();
alert.show();

And no need to dismiss the dialog, cause its the default behavior of AlertDialog.Let me know its solved your problem. Thanks.