Search code examples
androidpopupback-buttonexit-code

didn't work exit pop up backbutton code


i want to display pop up when user press back button on home screen . but it is not working,and give no error. and i work on slider menu with this code

  public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();

    AlertDialog.Builder build = new AlertDialog.Builder(this);
    build.setTitle("Confirmation");
    Log.d("aaaaa", "msg");
    build.setMessage("Are you sure, you want to exit ?");
    final AlertDialog alertDialog = build.create();
    alertDialog.show();
    build.setPositiveButton("Ha (Yes)", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            alertDialog.dismiss();
            finish();
        }
    });
    build.setNegativeButton("Na (No)", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            alertDialog.dismiss();
        }
    });

Solution

  • you show the dialog before you set the yes/no buttons. You need to put alertDialog.show(); at the end. Also get rid of super.backPressed(). You do not need it since you are override this original functionality.