How to set warning alert on back button click Android Studio app

After working and searching for hours and you can’t get the solution you are looking for. You are welcome to the home of Android Developer. If you have being using Android Studio for writing Java apps, Java codes is everything sensitive raging from capital letters, punctuation errors, misspelled of words and plugin updates. 


Android Studio comes up with new updates always which depreciated the older once. A code you write today, use it and develop an app may be outdated and depreciated tomorrow. If you copy somebody’s code or forked a code from github, there are chances that the code which worked earlier won’t work again unless you do serious editing.

1. @Override 

public void onBackPressed() { 

       AlertDialog.Builder builder = new AlertDialog.Builder(this);                               builder.setMessage(“Are you sure you want to exit?”)  
                 .setCancelable(false) 
                 .setPositiveButton(“Yes”, new DialogInterface.OnClickListener() { 

                      public void onClick(DialogInterface dialog, int id) {                                                  YourActivity.this.finish(); } }) 

                .setNegativeButton(“No”, new DialogInterface.OnClickListener() {                             public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); 

        AlertDialog alert = builder.create(); alert.show(); }

2. @Override

public void onBackPressed() { //if user presses the back button do this

if (webview.isFocused() && webview.canGoBack()) { //check if in webview and the user can go back

webview.goBack(); //go back in webview

} else { //do this if the webview cannot go back any further

new AlertDialog.Builder(this) //alert the person knowing they are about to close

.setTitle(“You are about to close the application”)

.setMessage(“You cannot go back any further, would you like to close?”)

.setPositiveButton(“Yes”, new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

finish();

}

})

.setNegativeButton(“No”, null)

.show();

}


3 see another method
@Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(“Are you sure you want to exit?”)
                .setCancelable(false)
                .setPositiveButton(“Yes”, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        MainActivity.this.finish();
                    }
                })
                .setNegativeButton(“No”, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();


    }