user3203327
user3203327

Reputation:

AlertDialog not showing in android code while trying to show alert dialog

I have a code which is shown but I am facing a problem to show an alert dialog. please help me to point out the problem

 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    context);

                // set title
                alertDialogBuilder.setTitle("Your Title");

                // set dialog message
                alertDialogBuilder
                    .setMessage("Click yes to exit!")
                    .setCancelable(false)
                    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, close
                            // current activity
                            MainActivity.this.finish();
                        }
                      })
                    .setNegativeButton("No",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });

                                    alertDialogBuilder.show();

Upvotes: 2

Views: 90

Answers (3)

T.V.
T.V.

Reputation: 793

Here's an example of an alert dialog with OK and Cancel Button:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());

alertDialogBuilder.setTitle("Your Tile");

alertDialogBuilder
    .setMessage("Your Message")
    .setCancelable(false)
    .setPositiveButton("Ok",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
        // OK Button

        }
        })
    .setNeutralButton("Cancel",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
             dialog.cancel();   
                }
        });

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

Upvotes: 1

Jitesh Upadhyay
Jitesh Upadhyay

Reputation: 5260

you have a problem with the code, please have a look alertDialogBuilder.show();

instead of this line please use

AlertDialog alertDialog = alertDialogBuilder.create();


                alertDialog.show();

hope it will help you

Upvotes: 0

Francois Morier-Genoud
Francois Morier-Genoud

Reputation: 659

You need to create it before showing it

AlertDialog alertDialog = alertDialogBuilder.create();

Upvotes: 4

Related Questions