Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dialog shown twice when back button pressed

In code the dialog is shown two times when i press the back button. Can anyone please tell me how to get the dialog only once?

public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK))
        {
            onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
         }

public void onBackPressed()
    {

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Do you want to save configuration?");
            builder.setPositiveButton
                           ("Yes", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int id)
                {
                //here saveConfiguration is boolean type    
                    if (saveConfiguration()) 

                                              {
                        dialog.dismiss();
                        finish();

                    }
                    else
                    {
                        dialog.dismiss();
                    }

                }
            });
            builder.setNegativeButton("No", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int id)
                {
                    dialog.dismiss();
                    finish();
                }
            });
            builder.show();
    }



}
like image 846
akhil2003in Avatar asked May 10 '11 07:05

akhil2003in


2 Answers

Your dialog is coming twice because it is consuming two events from back key i.e. key down and key up .. restrict that to any one of them ..

             if (event.getAction() != KeyEvent.ACTION_DOWN)
 {

      /* Now call onBackPressed method here */
 }
like image 85
Shachillies Avatar answered Oct 31 '22 21:10

Shachillies


onBackPressed() is a standart Activity method

What you are doing, is calling this method from onKeyDown manually, and then calling it again by delegataing event further via super.onKeyDown(keyCode, event) (which registers, that you pressed back and calls onBackPressed() automatically);

If you want to work with key back pressed event, thet either remove the onKeyDown method entierly and use only onBackPressed(), or rename your onBackPressed() to be something unique.

like image 25
Alex Orlov Avatar answered Oct 31 '22 20:10

Alex Orlov