简体   繁体   中英

Cannot dismiss the alert dialog box in android

I have an issue in dissmissing the alertdialog box which is customized. That is it is having a customized view that contains two buttons one is for db operation and other for loading another activity.I want to dissmiss the dialog box after the db action performed. But now i cant declare any command like dialog.dismiss() or cancel() or finish() please somebody help me to fix this.

My Class

  @Override
   protected boolean onTap(int index) {
     OverlayItem item = mapOverlays.get(index);
     final String  title= item.getTitle();
     final String snippet= item.getSnippet();
     AlertDialog.Builder dialog = new AlertDialog.Builder(this.context);
     if(title.equalsIgnoreCase("Your Location")){
     dialog.setTitle(item.getTitle());
     dialog.setMessage(item.getSnippet());
     dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        }
    });
     }
     else if(title.equalsIgnoreCase("")){
     LinearLayout layout = new LinearLayout(context);
     layout.setOrientation(LinearLayout.VERTICAL);

     final Button park_button = new Button(context);
     park_button.setHint("Park here");
   //  park_button.setBackgroundResource();
     layout.addView(park_button);
     park_button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            System.out.println("parkbutton:Clicked");
            // Delete DB Values
            int count = db.getDatasCount();
            for(int i = 0;i<count;i++){
                db.deleteValues(i);
            }
            //latitude & longtitude (string)
               String latitude = String.valueOf(lat);
               String longtitude = String.valueOf(lon);
               Log.d("Insert: ", "Inserting ..");
               db.addData(new Datas(latitude, longtitude));
              // Toast.makeText(context, "Lat: " + lat + ", Lon: "+lon, Toast.LENGTH_SHORT).show();

            // Reading DB Data
               Log.d("Reading: ", "Reading all Values...");
               List<Datas> datas = db.getAllDatas();       

               for (Datas dat : datas) {
                   String log = "Id: "+dat.getID()+" ,Latitude: " + dat.getlat() + " ,Longtitude: " + dat.getlon();
                       // Writing DB data to log
               Log.d("DB Data: ", log);
           }
            Intent f = new Intent(context,MainTabActivity.class);
            context.startActivity(f);
        }
    });


     final Button know_more_button = new Button(context);
     know_more_button.setHint("Know more");
     //  park_button.setBackgroundResource();
     layout.addView(know_more_button);
     know_more_button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            SharedPreferences prefs = context.getSharedPreferences("myprefs", 0);
            SharedPreferences.Editor editor =prefs.edit();
            editor.putString("KEY_REFERENCE", snippet);
            editor.commit();                

            Intent intent = new Intent(context, SinglePlaceActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    });

     dialog.setView(layout);
     dialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
     }
     dialog.show();
     return true;
   }

   public void addOverlay(OverlayItem overlay) {
      mapOverlays.add(overlay);
   }

   public void populateNow(){
       this.populate();
   }

}

First off, to explain how to get the behavior you want, I'll need you to rename your AlertDialog.Builder instance, currently named dialog , to builder . It's not accurately named and will help you understand my approach to solving your problem. So this line:

AlertDialog.Builder dialog = new AlertDialog.Builder(this.context);

would turn into:

AlertDialog.Builder builder = new AlertDialog.Builder(this.context);

From there, you'll need to:

  1. Create a final reference to the AlertDialog instance that is returned to you when you call show() - and call it dialog .
  2. Next, move the button click listeners you've set up down beneath where you call show() on the builder.
  3. Finally, reference the dialog var I had you create, and call dismiss() on that.

See code below:

// ... original code here (right before the end of your onTap main method)
final AlertDialog dialog = builder.show(); // this line used to be "dialog.show();"
know_more_button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // ... original code here
        dialog.dismiss();
    }
});
// ... for the other button, do the same
return true;

Try to extend DialogFragment if it is acceptable (you need to extend your activity from FragmentActivity).

public static class Dialog extends DialogFragment {

    @Override
    public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder b = new AlertDialog.Builder(getActivity());

        Button btn = new Button(getActivity());
        btn.setText("dismiss");

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        b.setView(btn);
        b.setPositiveButton("OK", null);
        return b.create();
    }
}

You can show dialog in this way (android.support.v4 is used):

new Dialog().show(getSupportFragmentManager(), "dialog");

Also you need establish communication between dialog and activity.

do this

final AlertDialog.Builder dialog = new AlertDialog.Builder(this.context);

not AlertDialog.Builder dialog = new AlertDialog.Builder(this.context);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM