Home » Android » core » ui » AlertDialog » Android Alert Dialog Example

About Katerina Zamani

Katerina Zamani
Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.

Android Alert Dialog Example

Sometimes in our applications we want to alert the user for an event and/or ask him/her about taking a decision. For this purpose AlertDialog class can be used, where a message and one, two or three buttons are displayed in a popup window.

In this example, we are going to show an AlertDialog with three different buttons, where each one leads to a different action.


For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SDK 4.4

1. Create a New Android Application Project

Open Eclipse IDE and go to File → New → Project → Android Application Project.

Fill in the name of the application, the project and the package in the appropriate fields and then click Next.


In the next window, check the “Create Activity” option. The new created activity will be the main activity of your project. Then press Next button.


In “Configure Launcher Icon” window you should choose the icon you want to have in your app. We will use the default icon of android, so press Next button.


Select the “Blank Activity” option and click Next.


Specify a name for the new Activity and a name for the layout description of your app. The .xml file for the layout will automatically be created in the res/layout folder. Finally, click Finish.


You can see the structre of the AlertDialogTest project in the picture below.


2. Create the layout of the Main Activity

We will create a simple interface, so we will add a TextView and a Button, which enables the AlertDialog box.

Open res/layout/activity_main.xml file and go to the xml tab. Then paste the following.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    tools:context=".MainActivity" >

        android:text="Main activity of the app..." />

        android:text="Show Alert Box" />


3. Code the Main Activity

AlertDialog is a subclass of Dialog that can display up to three Buttons. In order to create the interface of the alert box, AlertDialog.Builder should be called. AlertDialogBuilder class provides us positive, negative and neutral buttons by setting the setPositiveButton, setNegativeButton and setNeutralButton listeners respectively. At this point it is good to mention that the neutral button appears between the negative and the positive buttons.

In our example, we will use the three listeners. If the user chooses the positive button, a new Activity will launch by enabling an explicit Intent. In contrast, if the user presses the negative button, the alert box will close and we will go back to the main activity of our app. Finally, when the user clicks the neutral button, our application will close and it will lead the user to HOME.

Open src/com.javacodegeeks.android.alertdialogtest/MainActivity.java file and paste the following code.


package com.javacodegeeks.android.alertdialogtest;

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

public class MainActivity extends Activity {

	private Button mainBtn;
	protected void onCreate(Bundle savedInstanceState) {
		mainBtn = (Button) findViewById(R.id.button);	
		mainBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
	private void openAlert(View view) {
		 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
		 alertDialogBuilder.setTitle(this.getTitle()+ " decision");
		 alertDialogBuilder.setMessage("Are you sure?");
		 // set positive button: Yes message
		 alertDialogBuilder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					// go to a new activity of the app
					Intent positveActivity = new Intent(getApplicationContext(),
		 // set negative button: No message
		 alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					// cancel the alert box and put a Toast to the user
					Toast.makeText(getApplicationContext(), "You chose a negative answer", 
		 // set neutral button: Exit the app message
		 alertDialogBuilder.setNeutralButton("Exit the app",new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					// exit the app and go to the HOME
		 AlertDialog alertDialog = alertDialogBuilder.create();
		 // show alert


4. Crete a Custom Activity

We will create a new Activity for the explicit Intent of the positive answer.

To do so right click on com.javacodegeeks.android.alertdialogtest package → New → Class. Specify the name (PositiveActivity as we defined it in the MainActivity file) and the package that will belong to and finally click Finish.


Open src/com.javacodegeeks.android.alertdialogtest/PositiveActivity.java file and paste the code below.


package com.javacodegeeks.android.alertdialogtest;

import android.app.Activity;
import android.os.Bundle;

public class PositiveActivity extends Activity {
	   protected void onCreate(Bundle savedInstanceState) {


5. Create the layout of the Custom Activity

We are going to create a simple UI for the layout of the PositiveActivity class.

Right click on res/layout → New → Android XML File. Then, specify the name of the file and choose LinearLayout as root element, like in the image below. Then click Finish.


Open res/layout/positive_view.xml and paste the following.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" >

        android:text="You chose a positive answer..." />


6. Define the rules for the Custom Activity

We have to define the PositiveActivity activity in our AndroidManifest.xml file. In our occasion, we want PositiveActivity to leads us back to the MainActivity, so we will define the MainActivity as it’s parent Activity. For this reason parentActivityName android element is used.

Open AndroidManifest.xml file and choose the xml tab. Then paste the following code.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionName="1.0" >

        android:targetSdkVersion="19" />

        android:theme="@style/AppTheme" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
         	android:label="Positive Answer"
         	android:parentActivityName="com.javacodegeeks.android.alertdialogtest.MainActivity" >


7. Run the application

To run our application, right click on our project → Run as → Android Application. The AVD will appear with the app loaded, as you can see below.


Now press the “Show Alert Box” button. An alert box will popup and the user should take a decision, in order to proceed. Notice that the buttons don’t appear in the order we set them at the MainActivity.java, because Android system defines the button order as NEGATIVE - NEUTRAL - POSITIVE.


If we click the “No” button, the alert box will be canceled and the user will go back to the MainActivity with the appearance of a Toast, as you can see in the next picture.


When the user presses the “Yes” button, the setPositiveButton listener will be enabled, so the PositiveActivity will launch.


Now we can go back at the parent Activity, by pressing the button at the top left of the screen.

Finally, if we press “Exit the app” button, our app will close down and we will get lead to the main screen of the emulator.


Of course, the user can choose and launch this application again.

Download Eclipse Project

This was an example of Alert Dialog in Android. Download the Eclipse Project of this example: AlertDialogTest.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....



Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.