How do I display an alert dialog on Android? How do I display an alert dialog on Android? android android

How do I display an alert dialog on Android?


You could use an AlertDialog for this and construct one using its Builder class. The example below uses the default constructor that only takes in a Context since the dialog will inherit the proper theme from the Context you pass in, but there's also a constructor that allows you to specify a specific theme resource as the second parameter if you desire to do so.

new AlertDialog.Builder(context)    .setTitle("Delete entry")    .setMessage("Are you sure you want to delete this entry?")    // Specifying a listener allows you to take an action before dismissing the dialog.    // The dialog is automatically dismissed when a dialog button is clicked.    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {        public void onClick(DialogInterface dialog, int which) {             // Continue with delete operation        }     })    // A null listener allows the button to dismiss the dialog and take no further action.    .setNegativeButton(android.R.string.no, null)    .setIcon(android.R.drawable.ic_dialog_alert)    .show();


Try this code:

AlertDialog.Builder builder1 = new AlertDialog.Builder(context);builder1.setMessage("Write your message here.");builder1.setCancelable(true);builder1.setPositiveButton(    "Yes",    new DialogInterface.OnClickListener() {        public void onClick(DialogInterface dialog, int id) {            dialog.cancel();        }    });builder1.setNegativeButton(    "No",    new DialogInterface.OnClickListener() {        public void onClick(DialogInterface dialog, int id) {            dialog.cancel();        }    });AlertDialog alert11 = builder1.create();alert11.show();


The code which David Hedlund has posted gave me the error:

Unable to add window — token null is not valid

If you are getting the same error use the below code. It works!!

runOnUiThread(new Runnable() {    @Override    public void run() {        if (!isFinishing()){            new AlertDialog.Builder(YourActivity.this)              .setTitle("Your Alert")              .setMessage("Your Message")              .setCancelable(false)              .setPositiveButton("ok", new OnClickListener() {                  @Override                  public void onClick(DialogInterface dialog, int which) {                      // Whatever...                  }              }).show();        }    }});