Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity onBackPress not showing alert dialog

I have an Activity in which when I press back button then its not showing alert dialog. What could be the problem? Here is my code

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

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LogFish.this);

                // set title
                alertDialogBuilder.setTitle("Exit");
                alertDialogBuilder.setIcon(R.drawable.ic_action_search);

                // set dialog message
                alertDialogBuilder
                    .setMessage("This action will cause you to abandon all changes on current new fish log. \n\nAre you sure you want to exit?")
                    .setCancelable(false)
                    .setPositiveButton("YES",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, close
                            startActivity(new Intent(LogFish.this,MainActivity.class));
                            finish();

                        }
                      })
                    .setNegativeButton("NO",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close

                            dialog.cancel();
                        }
                    });

                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();

                    // show it
                    alertDialog.show();

                    }
like image 391
sumit acharya Avatar asked Dec 26 '12 13:12

sumit acharya


2 Answers

You have to Remove super.onBackPressed();

like image 100
Arash GM Avatar answered Nov 16 '22 18:11

Arash GM


@Override
public void onBackPressed() {

    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Title");
    builder.setMessage("Your Message");
    builder.setIcon(android.R.drawable.ic_dialog_alert);

    builder.setPositiveButton("YES", new OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            //implement your logic for YES
        }
    });

    builder.setNegativeButton("NO", new OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            //implement your logic for NO
        }
    });
    builder.setOnCancelListener(null);
    builder.show();
}
like image 2
Salman Zaidi Avatar answered Nov 16 '22 19:11

Salman Zaidi