Search code examples
androidandroid-alertdialogonkeydownonbackpressed

OnBackPressed doesn't display alert


I tried to override the onkeydown() method along with the onBackPressed() method but the alert dialog box doesn't appear instead it just goes back to the previous intent.I tried a several examples but none of them worked.

 @Override
     public boolean onKeyDown(int keyCode, KeyEvent event) {
          if (keyCode == KeyEvent.KEYCODE_BACK) {
        onBackPressed();

      }

      return super.onKeyDown(keyCode, event);
   }

      @Override
       public void onBackPressed() {


       Log.d("confirm save method","");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

           builder.setTitle("");
           builder.setMessage("Do you want to Save the Game ?");
           builder.setCancelable(false);
               builder.setPositiveButton("YES",
                 new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int which) {
                    finish();
                    System.exit(0);
                }
            });

    builder.setNegativeButton("NO",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

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


            Log.d("confirm save method","");

}


Solution

  • @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to exit?")
                .setTitle("Exit Alert")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
    
                        //finishAffinity(); 
                        finish();  //or do anything
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
    

    try this code, and also remove your onKeyDown();