TrinityTuts

Android Alert and progress dialog

Last updated on July 31st, 2016 at 11:16 am

Dialog box is used to allow user to confirm some thing or used to enter some information. In this post i explain you how to create alert dialog and progress dialog in android.

Alert Box in Android


1. Create new android project.

2. Open your layout file inside layout folder (eg. mainactivity.xm).

3. Create a button in layout

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/alert"
        android:id="@+id/alert" />

 4. Now open your java file MainActiviy.java . In this file we use AlertDialog.Builder to create the alert box interface, like title, message to display, buttons, and button onclick function. First create a variable for button and after find button on layout and when user click we create alert box. In this you also add more button to add button follow this link 

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

        // Alert Dialog
        alt = (Button) findViewById(R.id.alert);
        alt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder alertdialog = new AlertDialog.Builder(context);
                alertdialog.setTitle("Trinity Tuts"); // Alert Box Title
                alertdialog.setMessage("Best programming tutorial")
                        .setPositiveButton("Ok", 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();
                            }
                        });

                AlertDialog alt = alertdialog.create();
                alt.show();
            }
        });
}

Progress Dialog or Progress Bar Dialog Android

Progress dialog is used in android to show the progress of uploading and downloading of file. Progress bar is very easy to create. Please follow above step 1, 2, 3. Get button and start loading something i create a simple example so i am not loading anything but show you how to load. You need ProgressDialog to create this. You also read more about ProgressDialog from this link

  // Progress ring dialog
        ring = (Button) findViewById(R.id.ring);
        ring.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final ProgressDialog progresRing = ProgressDialog.show(MyActivity.this, "Trinity Tuts", "Wait Loading...", true);
                progresRing.setCancelable(true);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(5000);
                        } catch (Exception e) {

                        }
                        progresRing.dismiss();
                    }
                }).start();
            }
        });

        bar = (Button)findViewById(R.id.bar);
        bar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progress = new ProgressDialog(view.getContext());
                progress.setCancelable(true);
                progress.setMessage("File downloading ...");
                progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progress.setProgress(0);
                progress.setMax(100);
                progress.show();

                //reset progress bar status
                progressBarStatus = 0;

                new Thread(new Runnable() {
                    public void run() {
                        while (progressBarStatus < 100) {

                            // process some tasks
                            progressBarStatus = doSomeTasks();

                            // your computer is too fast, sleep 1 second
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            // Update the progress bar
                            progressBarHandler.post(new Runnable() {
                                public void run() {
                                    progress.setProgress(progressBarStatus);
                                }
                            });
                        }

                        // ok, file is downloaded,
                        if (progressBarStatus >= 100) {

                            // sleep 2 seconds, so that you can see the 100%
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            // close the progress bar dialog
                            progress.dismiss();
                        }

                    }
                }).start();

            }

            private int doSomeTasks() {
                while (fileSize <= 1000000) {

                    fileSize++;

                    if (fileSize == 100000) {
                        return 10;
                    } else if (fileSize == 200000) {
                        return 20;
                    } else if (fileSize == 300000) {
                        return 30;
                    }
                    // ...add your own

                }

                return 100;
            }
        });

Complete Code

mainactivity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MyActivity"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/alert"
        android:id="@+id/alert" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/progressA"
        android:id="@+id/ring"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/progressbar"
        android:id="@+id/bar"/>

</LinearLayout>

MainActivity.java

package com.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MyActivity extends Activity {

    Button alt, ring, bar;
    final Context context = this;
    ProgressDialog progress;
    private int progressBarStatus = 0;
    private long fileSize = 0;
    private Handler progressBarHandler = new Handler();

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

        // Alert Dialog
        alt = (Button) findViewById(R.id.alert);
        alt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder alertdialog = new AlertDialog.Builder(context);
                alertdialog.setTitle("Trinity Tuts"); // Alert Box Title
                alertdialog.setMessage("Best programming tutorial")
                        .setPositiveButton("Ok", 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();
                            }
                        });

                AlertDialog alt = alertdialog.create();
                alt.show();
            }
        });

        // Progress ring dialog
        ring = (Button) findViewById(R.id.ring);
        ring.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final ProgressDialog progresRing = ProgressDialog.show(MyActivity.this, "Trinity Tuts", "Wait Loading...", true);
                progresRing.setCancelable(true);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(5000);
                        } catch (Exception e) {

                        }
                        progresRing.dismiss();
                    }
                }).start();
            }
        });

        bar = (Button)findViewById(R.id.bar);
        bar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progress = new ProgressDialog(view.getContext());
                progress.setCancelable(true);
                progress.setMessage("File downloading ...");
                progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progress.setProgress(0);
                progress.setMax(100);
                progress.show();

                //reset progress bar status
                progressBarStatus = 0;

                new Thread(new Runnable() {
                    public void run() {
                        while (progressBarStatus < 100) {

                            // process some tasks
                            progressBarStatus = doSomeTasks();

                            // your computer is too fast, sleep 1 second
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            // Update the progress bar
                            progressBarHandler.post(new Runnable() {
                                public void run() {
                                    progress.setProgress(progressBarStatus);
                                }
                            });
                        }

                        // ok, file is downloaded,
                        if (progressBarStatus >= 100) {

                            // sleep 2 seconds, so that you can see the 100%
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            // close the progress bar dialog
                            progress.dismiss();
                        }

                    }
                }).start();

            }

            private int doSomeTasks() {
                while (fileSize <= 1000000) {

                    fileSize++;

                    if (fileSize == 100000) {
                        return 10;
                    } else if (fileSize == 200000) {
                        return 20;
                    } else if (fileSize == 300000) {
                        return 30;
                    }
                    // ...add your own

                }

                return 100;
            }
        });
    }


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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}