Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Android ProgressDialog Example

Progress dialogs are very commonly used components in all User Interfaces, when you want to display the progress of a task that is taking up a lot of time, for example a file or an Image download. In this tutorial will create a ProgressDialog to let the user know the progress and a status of a simulated Image download activity. We will  demonstrate both the Ring and the Bar style of the ProgressDialog component, as well as the use of special tools like Handler to update the value ( progress…) of the bar format.

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 SKD 4.2

1. Create a new Android Project

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

create-new-application

You have to specify the Application Name, the Project Name and the Package name in the appropriate text fields and then click Next.

create-new-project

In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.

check-create-new-activity

Select “BlankActivity” and click Next.

You will be asked to specify some information about the new activity.  In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml will be created. Then, click Finish.

3. Creating the layout of the Main Activity

Open res/layout/main.xml file :

main-xml

And paste the following code :

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/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="launchBarDialog"
        android:text="ProgressDialog Bar" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="launchRingDialog"
        android:text="ProgressDialog Ring" />

</LinearLayout>

Now you may open the Graphical layout editor to preview the User Interface you created:

graphical-layout-efitor

4. Code

Now we have to write the code of the application. Use the Package Explorer to navigate to the Java file of the Activity you’ve created:

main-src-file

The basic idea of the progress dialog is to display the status of a time consuming activity while that activity takes place. The most common way to do that is to use a thread that will do all the work, in our case simulate the downloading of a file, and update the UI (that is the progress bar) using a Handler. The Handler takes a Runnable object and it schedules its execution; it places the runnable process as a job in an execution queue to be run after a specified amount of time. The runnable will be run on the thread to which this handler is attached. In our case the handler is registerd in the main thread.

Go to the java file that contains the code of the activity you’ve just created and paste the following code:

MainActivity.java:

package com.javacodegeeks.android.androidprogressdialogexample;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

public class MainActivity extends Activity {

	ProgressDialog barProgressDialog;
	Handler updateBarHandler;

	@Override
	public void onCreate(Bundle savedInstanceState) {

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

		updateBarHandler = new Handler();
	}

	public void launchRingDialog(View view) {
		final ProgressDialog ringProgressDialog = ProgressDialog.show(MainActivity.this, "Please wait ...",	"Downloading Image ...", true);
		ringProgressDialog.setCancelable(true);
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					// Here you should write your time consuming task...
					// Let the progress ring for 10 seconds...
					Thread.sleep(10000);
				} catch (Exception e) {

				}
				ringProgressDialog.dismiss();
			}
		}).start();
	}

	public void launchBarDialog(View view) {
		barProgressDialog = new ProgressDialog(MainActivity.this);

		barProgressDialog.setTitle("Downloading Image ...");
		barProgressDialog.setMessage("Download in progress ...");
		barProgressDialog.setProgressStyle(barProgressDialog.STYLE_HORIZONTAL);
		barProgressDialog.setProgress(0);
		barProgressDialog.setMax(20);
		barProgressDialog.show();

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {

					// Here you should write your time consuming task...
					while (barProgressDialog.getProgress() <= barProgressDialog.getMax()) {

						Thread.sleep(2000);

						updateBarHandler.post(new Runnable() {

                            public void run() {

                            	barProgressDialog.incrementProgressBy(2);

                              }

                          });

						if (barProgressDialog.getProgress() == barProgressDialog.getMax()) {

							barProgressDialog.dismiss();

						}
					}
				} catch (Exception e) {
				}
			}
		}).start();
	}
}

The Handler component is a very interesting feature. Take a look at the Android Handler Documentation.

5. Run the application

This is the main screen of our Application:

main-screen

Now, when you press the “ProgressDialog Bar” button :

progress-bar

And after some time, the download is completed and the Progress Bar Dialog will close automatically… And when you press the “ProgressDialog Ring”:

progress-ring

Download Eclipse Project

This was an Android ProgressDialog Example. Download the Eclipse Project of this tutorial: AndroidProgressDialogExample.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 two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close