Android alert dialog example

In this tutorial, we show you how to display an alert box in Android. See flowing Steps :

  1. First, use the AlertDialog.Builder to create the alert box interface, like title, message to display, buttons, and button onclick function
  2. Later attach above builder to AlertDialog and display it.
  3. Done.

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1 Android Layout Files

Simpel layout file, display a button on screen.

File : res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Button
        android:id="@+id/buttonAlert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Alert Box" />
            
</LinearLayout>

2. Activity

When user click on this button, display the alert box, with your pre-defined alert dialog interface.

File : MainActivity.java


package com.mkyong.android;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	final Context context = this;
	private Button button;

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		button = (Button) findViewById(R.id.buttonAlert);

		// add button listener
		button.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View arg0) {

			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();
					}
				});

				// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();

				// show it
				alertDialog.show();
			}
		});
	}
}

3. Demo

Start it, display a button.

android alert box example

When button is clicked, display the alert box

android alert box example

If “Yes” button is clicked, close the activity and return back to your Android main screen.

android alert box example

Download Source Code

Download it – Android-Alert-Dialogl-Example.zip (16 KB)

References

  1. Android AlertDialog Javadoc
  2. Android Dialog example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Roy
Guest
Roy

If i want to display the the alert dialog again i have a user/password login alert box and if authentication fails then display it again

Nagaraj Nidagundi
Guest
Nagaraj Nidagundi

Thank You , Thank You Very Much Teacher,,,,,,,,,,,,,,

Om Dave
Guest
Om Dave

Superb..Sir Thanx lot Today is my first Day with Android and i learnt a lot…

Anu_143#
Guest
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??

D.Castt
Guest
D.Castt

Thanks mate, very concise.

Vino
Guest
Vino

Thanks a ton :)

Ahmed Soliman Flasha
Guest
Ahmed Soliman Flasha

Thank u very much

Grebenko Alex
Guest
Grebenko Alex

Thanks a lot, tutorial is great!

Chris
Guest
Chris

thanks for this great help
finally i can finish this project :)

Edward Warren
Guest
Edward Warren

Very well done. Thank you for taking the time to do this.

Simao
Guest
Simao

Thanks a lot, that helped me!

Simao
Guest
Simao

PositiveButton has to be Yes and NegativeButton has to be no

suresh kumar
Guest
suresh kumar

hi , sir why u not add Search box in your site for searching. (custom search box)?? it’s good way for any thing serach for related your content

Madhavan Malolan
Guest
Madhavan Malolan

Is it possible to have a alert dialog shown up on top of the Native Android Phone app when a call is in progress? If yes can you please guide me how? Thanks in advance :)

Yahya
Guest
Yahya

Thanks

Vinoj John Hosan
Guest
Vinoj John Hosan

Easy and quick… Thank you

John
Guest
John

Thanks! This really helped me out =]

Henry
Guest
Henry

Thanks for giving us a simple and easy to understand example. But if you’re looking for more Android AlertDialog example, take a look at this http://www.codeofaninja.com/2011/07/android-alertdialog-example.html

Ganmo
Guest
Ganmo

Hi, I notice that you create the AlertDialog directly in the main activity. Is this the normal way to go. Because in a way I think creating too many things in the main activity will clutter it. Should it be created in XMLs instead? Hope you understand what I mean.

red1
Guest
red1

thank you, it’s really helpful

farhan shah
Guest
farhan shah

Nice Work..Thanks Alot for Saving my time..

Pratik Shah
Guest
Pratik Shah

How to use intent in alert dialog box?

dzerry
Guest
dzerry

Thank you so much. It helps a lot. God Bless you

vipul
Guest
vipul

This is working perfectly. But I have one question. Developer.android.com says alertDialogs can work in API>11. so how is this working in Android 2.3.3?

kush ahuja
Guest
kush ahuja

hello , there seems to be another out of the world problem with me.
-Every time i run the application it gets compiled up nicely and launches the application but as soon as i hit the “button” on app it says the application has stopped unfortunately.
-This kinda things happen with my other applications also sometime even though there’s no error neither any kind of warning in the project.

I’ll b e looking forward for your help.

fuck@fucker.com
Guest
fuck@fucker.com

Ass hole

Phaggot
Guest
Phaggot

LOL you’re a faggot, cunt

computer coupons australia
Guest
computer coupons australia

Hi, i think that i saw you visited my weblog so i came to _return the favor_.
I’m attempting to find things to improve my website!I suppose its ok to use some of your ideas!!

El
Guest
El

Thanks for the tips!

Cheers!

Somesh
Guest
Somesh

Very good code. May I have your mail id to contact my queries

trackback
I want to add a pop-up dialogue box in my android app : Android Community - For Application Development