HOW TO CREATE ALERTDIALOG IN ANDROID?

Ankita Pandey

Total Post:183

Points:1285
Posted by  Ankita Pandey
 885  View(s)
Ratings:
Rate this:
Iam Showing a AlertDialog on Device Shake. The issue is that when I shake the device the AlertDialog shows twice. Hence, if I dismiss the AlertDialog, the top one gets dismissed but there is one still showing after that behind the first one.

Also, Iam showing the same AlertDialog from another section of code where it is shown on a button click which works fine.

All of this is done within a ViewPager.

How can I avoid this scenario?

Here is my code:-

@Override
public void onShake(float force) 
{
    // TODO Auto-generated method stub
    showDialog(timeString, "Confirm .");
}
public void showDialog(String timeString, String title)
    {
        builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(title);
        builder.setMessage("Reaching at:"+" "+ timeString+"?");
        builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Do nothing
            }
        });
        builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) 
            {
                // Do nothing but close the dialog
                new AddStatusTask().execute();
            }
  1. Pravesh Singh

    Post:412

    Points:2888
    Re: How to create AlertDialog in android?

    Instead of builder.show();

    use

    // create alert dialog
    alertDialog = builder.create();

    // show it
    alertDialog.show();
    and check here like

    @Override
       public void onShake(float force) 
      {
    // TODO Auto-generated method stub

     if(alertDialog != null && !alertDialog.isShowing()){
    showDialog(timeString, "Confirm .");
    } }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!