-1

Am using below onBackpress method but this not working , am still click to back button repentantly came the same activity not exit current activity please solve my problem .

   @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        // Your Dialog Code is here.

        new AlertDialog.Builder(this)
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface arg0, int arg1) {
                        ProfileActivity.super.onBackPressed();
                        finish();
                    }
                }).create().show();
    }
Ronak Thakkar
  • 2,515
  • 6
  • 31
  • 45
Kathirsk
  • 23
  • 5

3 Answers3

1

Use .setCancelable(false) with AlertDialog,

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    // Your Dialog Code is here.

    new AlertDialog.Builder(this)
            .setMessage("Are you sure you want to exit?")
            .setCancelable(false)
            .setNegativeButton(android.R.string.no, null)
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface arg0, int arg1) {
                    ProfileActivity.super.onBackPressed();
                    finish();
                }
            }).create().show();
}
Sagar Zala
  • 4,854
  • 9
  • 34
  • 62
0

Remove ProfileActivity.super.onBackPressed(); it will work.

Shubham Vala
  • 1,024
  • 7
  • 18
  • You could also add `.setCancelable(false)` if you don't want to close the `AlertDialog` with back button if it's opened. – Prexx Jul 11 '18 at 10:42
0

remove this ProfileActivity.super.onBackPressed();

add

.setCancelable(false) 
faran.javed
  • 418
  • 2
  • 15