Question: I am trying to show a confirm AlertDialog before user press on back button or Activity going Pause.  

I tried this code:

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

    AlertDialog.Builder confirmBuilder=new AlertDialog.Builder(DoExam.this);
    confirmBuilder.setTitle("Confirm Exit");
    confirmBuilder.setMessage("are you sure to exit form this activity");
    confirmBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    confirmBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    AlertDialog confirmDialog=confirmBuilder.create();
    confirmDialog.show();
}

```

But it disappeared immediately at the same time the app back to previous activity.  

I tried also to put the code at onPause method but I got the same problem.

Any help about show alert dialog and back to previous activity if clicked yes and keep user in the Activity if clicked no?

Answer: 
Because you are calling `super.onBackPressed();` remove that and see what happens. the `super.onBackPressed();` is meant to trigger the default action of closing the activity. you need to defer that call when the user dismisses the dialog.
> 
> Remove `super.onBackPressed();` and add it in `onClick(...)` of your posetive **Yes** button of your Alertdialog..
> 
> 
> 

like this 

```
confirmBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) {         super.onBackPressed();

```

} });