ProgressDialog

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

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. 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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button