Creating alert dialog is very easy. In this tutorial i will be discussing about creating different alert dialogues with one button(ok button), two buttons(yes or no buttons) and three buttons(yes, no and cancel buttons).

Download Code

Android alert dialog with One button

The following code will create a simple alert dialog with one button. In the following code setTitle() method is used for set Title to alert dialog. setMessage() is used for setting message to alert dialog. setIcon() is to set icon to alert dialog.

AlertDialog alertDialog = new AlertDialog.Builder(
						AlertDialogActivity.this).create();

		// Setting Dialog Title
		alertDialog.setTitle("Alert Dialog");

		// Setting Dialog Message
		alertDialog.setMessage("Welcome to AndroidHive.info");

		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.tick);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
				// Write your code here to execute after dialog closed
				Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
				}
		});

		// Showing Alert Message
		alertDialog.show();

This output of about code will be like following image.

Alert Dialog with One button

Android alert dialog with two button

The following code will create alert dialog with two button. setPositiveButton() is used to create a positive button in alert dialog and setNegativeButton() is used to invoke negative button to alert dialog.

AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);

		// Setting Dialog Title
		alertDialog.setTitle("Confirm Delete...");

		// Setting Dialog Message
		alertDialog.setMessage("Are you sure you want delete this?");

		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.delete);

		// Setting Positive "Yes" Button
		alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int which) {

			// Write your code here to invoke YES event
			Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
			}
		});

		// Setting Negative "NO" Button
		alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,	int which) {
			// Write your code here to invoke NO event
			Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
			dialog.cancel();
			}
		});

		// Showing Alert Message
		alertDialog.show();

This output of about code will be like following image.

Alert Dialog with two buttons

Android alert dialog with three button

Here setNeutralButton() is used to create a neutral cancel button

AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);

				// Setting Dialog Title
				alertDialog.setTitle("Save File...");

				// Setting Dialog Message
				alertDialog.setMessage("Do you want to save this file?");

				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.save);

				// Setting Positive "Yes" Button
				alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					// User pressed YES button. Write Logic Here
					Toast.makeText(getApplicationContext(), "You clicked on YES",
										Toast.LENGTH_SHORT).show();
					}
				});

				// Setting Negative "NO" Button
				alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					// User pressed No button. Write Logic Here
					Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
					}
				});

				// Setting Netural "Cancel" Button
				alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					// User pressed Cancel button. Write Logic Here
					Toast.makeText(getApplicationContext(), "You clicked on Cancel",
										Toast.LENGTH_SHORT).show();
					}
				});

				// Showing Alert Message
				alertDialog.show();

This output of about code will be like following image.

Android alert dialog with three buttons
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • sidharth

    clear n simple.. cool ๐Ÿ™‚

  • srbkrishnan

    Will Alert Dialog work inside a class Implementing BroadcastListener??

  • Anish Bharatha

    is there any way to know if this message is being shown ?
    For Dialog class, isShowing() method returns true if the alert is shown to user.
    any clue ?

  • Sagar Vadaria90

    unable add window

  • Donna R.

    I get 3 buttons:
    “Choice A”, “Choice B”, “Cancel”, in Gingerbread.
    But in Jelly Bean I get it backwards: “Cancel”, “Choice B”, “Choice A”.

    How do I fix that?

    • PolskaGรณrฤ…

      Replace their names in code together with runnables ๐Ÿ˜‰

  • minhdangtran

    thanks you very much!

  • Marci

    Thank you very much! It’s working and it’s very simple… cool ๐Ÿ™‚

  • Irfan khan

    cool brother great work

  • Roney

    To learn ANDROID from the very beginning

    VISIT ANDROIDITUTS

    http://www.androidituts.com

    • Sonjay Singh

      Bookmark Added
      Done !!

  • ashish

    awesome explantion

  • sanjay

    very very help full tutorial…………

  • sanjay
    • vignesh

      How to change the theme of the alert dialog and adding image for button ?

  • very useful ๐Ÿ˜€ GBU admin nice ๐Ÿ˜€

  • GOH CHONG LOONG

    Bravo!!Ur tutorial gives the right solution!!!

  • Marvin

    thank you so much.

  • anonymous

    motherfuking article
    this aint executing u fucker atleast give some more details u asshole.

    • qqqq

      what resource type will be use? this dude is right, give more details for every article

    • dfdsf

      Haram jarea, nikal ja

  • Meghna

    Thanks for the clean explanation Ravi.. Even this http://www.compiletimeerror.com/2013/08/android-alert-dialog-example.html might be helpful, have a look…

  • Erhan Cetin

    Take a look here , this is my solution for it with source code:

    http://www.erhancetin.com.tr/2013/10/how-to-display-alert-dialog-in-android.html

  • studenttt

    Hi how do i start the NetAsync when pressed on positve button?

    I tried putting NetAsync(view); put theres error “Cannot refer to a non-final variable view inside an inner class defined in a different method”

  • george

    Hello. I need someone
    to develop a simple app. will use java , php and sql. please reply to george.celsie@gmail.com
    if you can help me. I will share the
    credits :). Thanks

  • hari

    i need to know how to do chat application

  • Dharmik

    You really did a great job. ๐Ÿ™‚

  • prajwal shetty

    Its working, thanks dude:)

  • Paqco Suarex

    That is exactly what I was looking for, Thank you!!!

  • Clemar

    Problem solved!!, Thanks!!

  • bteranv2

    Thank, It is very useful.

  • Thank it useful but provide .zip file of code

  • Mayank Sood

    my app crashes every time. any solution?

    • Daniel Baumert (HackerOnBoard)

      Use this import import android.support.v7.app.AlertDialog; and
      Builder(this); not Builder(getApplicationContext());

  • Mayank Sood

    app crashes, any solution?

    this is my code

    package com.techcuriosity.vcn;

    import com.techcuriosity.vcn.library.UserFunctions;

    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.Intent;

    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    /*import android.view.Menu; */

    public class LoginActivity extends Activity {

    TextView registerlink;
    Button loginBtn;
    EditText etUsername;
    EditText etPassword;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    //Toast.makeText(getApplicationContext(), “Invalid Email”, Toast.LENGTH_SHORT).show();
    registerlink = (TextView) findViewById(R.id.link_to_register);
    registerlink.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent i = new Intent(getApplicationContext(),RegisterActivity.class);
    startActivity(i);
    finish();
    }
    });
    loginBtn = (Button) findViewById(R.id.btnLogin);
    etUsername = (EditText) findViewById(R.id.etUserName);
    etPassword = (EditText) findViewById(R.id.etPassword);
    loginBtn.setOnClickListener(new View.OnClickListener() {

    @SuppressWarnings(“deprecation”)
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    String username = etUsername.getText().toString();
    String password = etPassword.getText().toString();
    AlertDialog.Builder builder = new AlertDialog.Builder(
    LoginActivity.this);
    builder.setTitle(“Sample Alert”);
    builder.setMessage(“Sample One Action Button Alert”);
    builder.setPositiveButton(“OK”,
    new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog,
    int which) {
    Log.e(“info”, “OK”);
    }
    });
    builder.show();
    //UserFunctions userFunction = new UserFunctions();
    }
    });
    }

    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.login, menu);
    return true;
    }
    */

    }

  • suresh reddy

    I have listview in my app when i am click on any one item in that listview how to get the alertdialog box send me any reference

  • Really It is good example. But when i use setPositiveButton or setNegativeButton. It causes error.

  • sanjeev

    Really good example.but how to use setpositive and negative bottom from layout.that means own customized buttom.

  • ashwini

    how to fetch username from database and display it into alertDialog

  • Millah

    thank you ravi… this tutorial very helpful

  • john

    hey…. i am try to create a automatic login frames for android an ios.. can u help me please…

  • Samar Hasan

    How could we view an image and txt in the dialog without buttons ๐Ÿ™‚

    • Use Dialog Fragment.

      • Samar Hasan

        thank’s ๐Ÿ™‚ but i try to put the code onitemclick of custom grid view but nothing appeared when click the item

      • daivaprasad

        I have 2 Buttons in Popup window…
        How can I display Dialog box when i click on button from the Popupwindow ?

  • Anu_143#

    Hi… I have been trying to edit some of the strings in my apk file,
    since I want to add some modified info in the app. But I am not able to
    edit them. Even if I make changes in strings.xml, there are certain
    errors that do not recompile my file. What am I suppose to do? it’s my
    project work and no one could help me around, please tell me how to edit
    these strings??

  • chandan kumar

    how can i seticon through drawable please reply fast anybody guyzz

  • honest hearts

    You are like my sifu. Give all the information that I need. Thanks.

  • ุฃู†ุง ุฃุญุจ ูŠุณูˆุน

    how to show alertdialog on navigation drawer when click the item menu?(logout menu)
    with positive and negative button

    • ุฃู†ุง ุฃุญุจ ูŠุณูˆุน

      problem solve……………….

      @SuppressWarnings(“StatementWithEmptyBody”)
      @Override
      public boolean onNavigationItemSelected(MenuItem item) {
      FragmentManager fm = getFragmentManager();
      AlertDialog alertDialog;
      int id = item.getItemId();

      if (id == R.id.Your_NAV_ID1) {

      alertDialog = new AlertDialog.Builder(this).create();
      alertDialog.setTitle(“YOUR TITLE”);
      alertDialog.setIcon(R.drawable.YOUR_IMAGE_TITLE);
      alertDialog.setMessage(Html.fromHtml(“YOUR MESSAGEYOUR MESSAGE”));
      alertDialog.setButton(Dialog.BUTTON_POSITIVE,”YOUR STRING BUTTON”,new DialogInterface.OnClickListener() {

      public void onClick(DialogInterface dialogInterface, int which) {
      Toast.makeText(getApplicationContext(), “YOUR TOAST”, Toast.LENGTH_SHORT).show();
      //////////////
      }

      } );
      alertDialog.setButton(Dialog.BUTTON_NEGATIVE,”OUR STRING BUTTON”,new DialogInterface.OnClickListener() {

      public void onClick(DialogInterface dialogInterface, int which) {
      Toast.makeText(getApplicationContext(), “YOUR TOAST”, Toast.LENGTH_SHORT).show();
      dialogInterface.cancel();
      }

      } );

      alertDialog.show();
      /////////CHANGE BUTTON FONT AND COLOR alertDialog.getButton(alertDialog.BUTTON_NEGATIVE).setTextColor(Color.parseColor(“#ffffff”));
      alertDialog.getButton(alertDialog.BUTTON_NEGATIVE).setBackgroundColor(Color.parseColor(“#000000”));
      alertDialog.getButton(alertDialog.BUTTON_POSITIVE).setTextColor(Color.parseColor(“#ffffff”));
      alertDialog.getButton(alertDialog.BUTTON_POSITIVE).setBackgroundColor(Color.parseColor(“#ff9600”));

      } else if (id == R.id.Your_NAV_ID2) {
      fm.beginTransaction().replace(R.id.content_frame, new YOUR_CLASS()).commit();

      }
      DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
      drawer.closeDrawer(GravityCompat.START);
      return true;
      }

  • Mesfun

    Thank very much i learn a lot from your Blog
    i create a listview inside alertbox an app i can not figure out how to choose items this is my file link is

    https://www.dropbox.com/sh/kbkgl5a10lz2kzf/AADwVn6CC4PRdjSz76l2DkYva?dl=0

    what i want is when you select Atlanta show a dialog box and choose red yellow and the same choose Texas and dialog choose yellow Brown

    click a button USA states Grow Flower and show only The following were selected Atlanta Texas

    but i want when i click

    a button to show me

    The following were selected Atlanta red,yellow Texas yellow,Brown

    incase if u figure out please email answer at mesfun@hotmail.com

  • Error Eliminator

    Nice simple way to explain difficult things…..

  • Julius Ndyakalika

    thanks