Android alert dialog example - npxcoding

In android, AlertDialog is a small message window that is a popup on the screen. AlertDialog can contain one message, title, icon, and buttons. 

One of the best examples of AlertDialog is no internet dialog. and AlertDialog can be dismissed by clicking on the dialog buttons or when we click on the background it disappears.

Android alert dialog example

In this tutorial, we will learn to implement AlertDialog in the android app using java. We will create a simple app and then we will implement AlertDialog on button click. 

So let's start it.

Here is the sample code of alert dialog :

new AlertDialog.Builder(context)
    .setTitle("Dialog Title")
    .setMessage("This is Dialog message!!")

    // 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("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            // Code
        }
     })

    // A null listener allows the button to dismiss the dialog and take no further action.
    .setNegativeButton("Cancel", null)
    .setIcon(android.R.drawable.ic_dialog_alert)
    .show();

Complete Example :


Layout design

Open android studio and create a new project or open your existing project. 

First, we have to design the activity_main.xml layout.

So according to your need, you should prepare the layout. But I'm designing the layout here on my own and there is only one button in it. Here's the code :


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/main_bg"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Dialog"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.25" />
</androidx.constraintlayout.widget.ConstraintLayout>

The AlertDialog will display when the button got clicked.


Java code

Designing is done. let's move on to the actual coding part. 

Open the MainActivity.java file and add the below code:


MainActivity.java

package com.example.simpleapp;

import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //initialize views
        button = findViewById(R.id.button);

        //button click listener
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               new AlertDialog.Builder(MainActivity.this)
                       .setTitle("Alert")
                       .setMessage("No internet connection!!")
                       .setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               Toast.makeText(MainActivity.this,"Positive button clicked",Toast.LENGTH_SHORT).show();
                           }
                       })
                       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.dismiss();
                               Toast.makeText(MainActivity.this,"Negative button clicked",Toast.LENGTH_SHORT).show();
                           }
                       })
                       .setCancelable(false)
                       .setIcon(R.drawable.no_internet_icon).show();
               ;
            }
        });


    }
}

Code Explanation :

First, initialize the views and set the click listener to the button.

Create the object of the " AlertDialog.Builder() " .


1. To set the title of the AlertDialog

new AlertDialog.Builder(MainActivity.this)
.setTitle("Alert");


2. To set the message of the AlertDialog

new AlertDialog.Builder(MainActivity.this)
.setMessage("No internet connection!!");


3. Positive Button

This is an affirmative button that is used to proceed further. For example, the OK button.

To set positive button -

new AlertDialog.Builder(MainActivity.this)
                       .setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               Toast.makeText(MainActivity.this,"Positive button clicked",Toast.LENGTH_SHORT).show();
                           }
                       });


4. Negative Button

This is a dismissive button that is used to cancel an action. For example, Cancel Button.

To set negative button -

new AlertDialog.Builder(MainActivity.this)
                       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.dismiss();
                               Toast.makeText(MainActivity.this,"Negative button clicked",Toast.LENGTH_SHORT).show();
                           }
                       });


5. Cancelable

new AlertDialog.Builder(MainActivity.this)
                       .setCancelable(false);

If the setCancelable is true :

the dialog will be dismissed if the user will click outside the dialog.

And if it is false then :

when we click on the background it will not disappear.


6. To set the icon of the AlertDialog

First, you have to add icons in your res folder and then you can set those icons to the dialog.
new AlertDialog.Builder(MainActivity.this)
                       .setIcon(R.drawable.no_internet_icon);


7. show method

the show() method will show the dialog.


8. Dismiss dialog

we can dismiss the dialog using :
dialog.dismiss();


Output



Add all code to your project and run the app. So the AlertDialog is displayed when the button is clicked. The negative and Positive buttons are also working perfectly. 

And note that, the dialog is not dismissing when clicking outside of the dialog it's because we had applied setCancelable() to false.

So in this way you can implement AlertDialog in the android app using java.

Leave a comment if you had any queries regarding this post and I will reply as soon as possible. Anyway, if you enjoy reading my content, you can subscribe to my blog to receive all the latest updates. Happy Learning!

Share this article with your friends ✌!!