I'l Follio
I'l Follio

Reputation: 573

AlertDialog always press Positive Button

I have an AlertDialog in an onBackPressed(), if I click the positive button it must launch an activity with an Intent.

@Override
    public void onBackPressed() {
        super.onBackPressed();

        android.app.AlertDialog.Builder logoutDialog = new android.app.AlertDialog.Builder(MainActivity.this);
        logoutDialog.setTitle("Logout");
        logoutDialog.setMessage("¿Are you sure that you want to exit? Your session will end."
        );

        logoutDialog.setPositiveButton("LOGOUT",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent i = new Intent(MainActivity.this, LoginActivity.class);
                        startActivity(i);
                        finish();
                    }
                }
        );
        logoutDialog.setNegativeButton("CANCEL",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }
        );
        logoutDialog.show();
    }

But when I press back the Dialog appears less than a second and then it goes to the expected activity but without pressing PositiveButton.

Upvotes: 0

Views: 43

Answers (2)

Fakhriddin Abdullaev
Fakhriddin Abdullaev

Reputation: 4940

just commit super.onBackPressed() it is finished your activity.

Upvotes: 0

Matthew Shearer
Matthew Shearer

Reputation: 2795

try removing super.onBackPressed();

@Override
public void onBackPressed() {
    //super.onBackPressed();

    android.app.AlertDialog.Builder logoutDialog = new android.app.AlertDialog.Builder(MainActivity.this);
    logoutDialog.setTitle("Logout");
    logoutDialog.setMessage("¿Are you sure that you want to exit? Your session will end."
    );

    logoutDialog.setPositiveButton("LOGOUT",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent i = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(i);
                    finish();
                }
            }
    );
    logoutDialog.setNegativeButton("CANCEL",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }
    );
    logoutDialog.show();
}

Upvotes: 2

Related Questions