ProgressBar

Android Progress Bar Example

The progress Bar is a very common component 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 download. In this tutorial will create a Progress Bar Dialog to let the user know the progress and a status of a simulated file download activity.
 
 
 
 
 
 
 
 
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. You have to specify the Application Name, the Project Name and the Package name in the appropriate text fields and then click Next.

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.

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.

2. Adding resources

Use the Package Explorer in Eclipse to navigate to res/values/strings.xml

When you open the strings.xml file, Eclipse will display the graphical Resources View editor :

That’s a nice and easy tool you can use to add several resources to your application like strings, integers, color values etc. But we are going to use the traditional way and that is editing the strings.xml file by hand. In the bottom of the screen, press the string.xml tab and paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ProgressBarExample</string>
    <string name="menu_settings">Settings</string>
    <string name="button_label">Download File</string>

</resources>

So, we’ve just created some string resources that we can use in many ways and in many places in our app.

3. Creating a Button

Open res/layout/main.xml file :

And paste the following code :

<?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/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_label" />

</LinearLayout>

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

4. Code

The basic idea of the progress bar 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 the main thread (the UI thread …) of our activity that launches when the OnCreate() method is executed. The “download” thread will enqueue the tasks of updating the Progress Bar status to the main thread by using a Handler.

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

package com.javacodegeeks.android.androidprogressbarexample;

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

public class MainActivity extends Activity {

	Button button;
	ProgressDialog progressBar;
	private int progressBarStatus = 0;
	private Handler progressBarbHandler = new Handler();

	private long fileSize = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		addButtonListener();

	}

	public void addButtonListener() {

		button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {

				// create and display a new ProgressBarDialog
				progressBar = new ProgressDialog(view.getContext());
				progressBar.setCancelable(true);
				progressBar.setMessage("File downloading ...");
				progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				progressBar.setProgress(0);
				progressBar.setMax(100);
				progressBar.show();

				progressBarStatus = 0;

				fileSize = 0;

				new Thread(new Runnable() {

					public void run() {
						while (progressBarStatus < 100) {

							// process some tasks
							progressBarStatus = downloadFile();

							// sleep 1 second (simulating a time consuming task...)
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}

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

						// if the 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();
							}

							// and then close the progressbar dialog
							progressBar.dismiss();
						}
					}
				}).start();

			}

		});

	}

	// file download simulator...
	public int downloadFile() {

		while (fileSize <= 1000000) {

			fileSize++;

			if (fileSize == 100000) {
				return 10;
				
			} else if (fileSize == 200000) {
				return 20;
				
			} else if (fileSize == 300000) {
				return 30;

			} else if (fileSize == 400000) {
				return 40;

			} else if (fileSize == 500000) {
				
				return 50;
			} else if (fileSize == 700000) {
				
				return 70;
			} else if (fileSize == 800000) {
				
				return 80;
			}
			//...

		}

		return 100;

	}

}

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:

Now, when you press the button :

And after some time, the download is completed and the Progress Bar Dialog will close automatically… :

Download Eclipse Project

This was an Android Progress Bar Example. Download the Eclipse Project of this tutorial: AndroidProgressBarExample.zip

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button