The progress bar is useful for telling users that your Android Application is working on a task that might take a little longer than the usual tasks.
A progress bar is quit easy to make, which I have described here is the Dialog Boxes post here and I will therefor not go into details with this.
Simple test layout
I have created a simple test layout like this:

XML layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Maximum value"></TextView>
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="100" android:id="@+id/maximum"></EditText>
<TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Increment by"></TextView>
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="5" android:id="@+id/increment"></EditText>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start" android:id="@+id/startbtn"></Button>
</LinearLayout>
There are two text fields. One to set the maximum value of the progress bar and one to set the increment value. When pushing the Start button a progress bar is displayed and in this example it will just update the progress bar every half a second (500ms) to demonstrate the result.
Updating the progress bar
To update the progress bar in the background, while something else is running the application has to use threads. I will be setting up a thread when the Start button is clicked. The thread will then execute some code, in this case just a simple handler that will update the progress bar, and when finished the thread will terminate itself.
When the Start button is activated the application will display a progress bar – I have set a maximum value of 200 and a increment value of 14:

Complete Java code
The complete java code looks like this. I have added comments in the code, so it should be self explanatory – if not just post a comment last on this page.
package huuah.progressthread;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.app.ProgressDialog;
public class progressthread extends Activity implements OnClickListener {
ProgressDialog dialog;
int increment;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button startbtn = (Button) findViewById(R.id.startbtn);
startbtn.setOnClickListener(this);
}
public void onClick(View view) {
// get the increment value from the text box
EditText et = (EditText) findViewById(R.id.increment);
// convert the text value to a integer
increment = Integer.parseInt(et.getText().toString());
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Loading...");
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// reset the bar to the default value of 0
dialog.setProgress(0);
// get the maximum value
EditText max = (EditText) findViewById(R.id.maximum);
// convert the text value to a integer
int maximum = Integer.parseInt(max.getText().toString());
// set the maximum value
dialog.setMax(maximum);
// display the progressbar
dialog.show();
// create a thread for updating the progress bar
Thread background = new Thread (new Runnable() {
public void run() {
try {
// enter the code to be run while displaying the progressbar.
//
// This example is just going to increment the progress bar:
// So keep running until the progress value reaches maximum value
while (dialog.getProgress()<= dialog.getMax()) {
// wait 500ms between each update
Thread.sleep(500);
// active the update handler
progressHandler.sendMessage(progressHandler.obtainMessage());
}
} catch (java.lang.InterruptedException e) {
// if something fails do something smart
}
}
});
// start the background thread
background.start();
}
// handler for the background updating
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(increment);
}
};
}

maj 1st, 2010 at 16:17
Hi, thanks for the great code. I use it in my project, but I get a NullPointerException at dialog.incrementProgressBy(1); Any ideas?
maj 1st, 2010 at 16:52
Hello Vince. I cannot say why you are gettng a NullPointerException, without seeing a bit more of your code.
maj 1st, 2010 at 17:24
I have a button and start the thread when handling the onClick event. I started learning about Android about a week ago and I like it very much. So I’m basically quite the newbie. Okay, here is some of the code:
public class Proba extends Activity implements OnClickListener {
ProgressDialog pdia;
…
…
public void onClick(View v1) {
switch (v1.getId()) {
case R.id.Button01:
ProgressDialog pdia = new ProgressDialog(this);
pdia.setCancelable(true);
pdia.setMessage(“Converting…”);
pdia.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pdia.setMax(240);
pdia.setProgress(0);
pdia.show();
Thread background = new Thread (new Runnable() {
public void run()
{
try {
progressHandler.sendEmptyMessage(0);
} catch (Exception e) {
Log.e(“PH”, “S: Error”, e);
}
}
});
background.start();
break;
}
}
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
pdia.incrementProgressBy(1);
}
};
I’ve changed to sendEmptyMessage(0) for some reason, but regardless of the sending method, the exception occurs in the handleMessage and specifically upon calling incrementProgressBy or any other method of pdia for that matter.
I have another question. I intend to do some heavy computation in that thread and want to pass the result as an int array. That should be done with another message, right?
Thanks!
maj 1st, 2010 at 17:35
That might be useful too:
========
E/AndroidRuntime( 1514): java.lang.NullPointerException
E/AndroidRuntime( 1514): at proben.Proba$1.handleMessage(Ekran.java:133)
E/AndroidRuntime( 1514): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 1514): at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime( 1514): at android.app.ActivityThread.main(ActivityThread.java:4363)
E/AndroidRuntime( 1514): at java.lang.reflect.Method.invokeNative(NativeMethod)
E/AndroidRuntime( 1514): at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime( 1514): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
E/AndroidRuntime( 1514): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
E/AndroidRuntime( 1514): at dalvik.system.NativeStart.main(Native Method)
===========
maj 1st, 2010 at 20:32
Argh, I don’t really know what’s wrong, but I’ve created a new project with the same code and it works like a charm! Sorry for bothering and again thanks for the code!
maj 1st, 2010 at 22:36
That’s okay – glad you got it working
juli 14th, 2010 at 11:55
Thanks a lot…all your code is helpfully for beinger like me………..Thanks alot once again….for such simple and easy code
august 5th, 2010 at 16:04
Hey , thanks for snippet on progress bar.
However, once the progress bar is reached 100, i wished to dispose the dialog, and used the method ” dialog.dismiss();”, this didn’t woked, could any of aware how could i do this?
Cheers
Arvind
august 5th, 2010 at 16:17
Hey dude1, i found hot to dismiss the dialog, here is updated one
// handler for the background updating
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(increment);
if(dialog.getProgress()== dialog.getMax())
{
dialog.dismiss();
}
}
august 5th, 2010 at 16:17
Arvind,
I have done a quick test and the dismiss() and the cancel() seems to be working just fine.
Code example:
// handler for the background updateing Handler progressHandler = new Handler() { public void handleMessage(Message msg) { if (dialog.getProgress() >= 100) { //dialog.cancel(); dialog.dismiss(); } else { dialog.incrementProgressBy(increment); } } };Reference to the cancel() call:
http://developer.android.com/reference/android/app/Dialog.html#cancel%28%29
Reference to the dismiss() call:
http://developer.android.com/reference/android/app/Dialog.html#dismiss%28%29
august 5th, 2010 at 16:21
Superb!
august 27th, 2010 at 16:23
Hi,
How could I create a progress bar to measure time of different video clip’s streaming/playing/pause/finish time of video?
januar 5th, 2011 at 07:51
can any 1 gimme da progress dialog code on a new screen with out any click events
januar 21st, 2011 at 15:35
Hi,
GREETINGS OF THE DAY
I am really happy see code like this. this really works at my end.
I am reading data from xml files and inserting in database. and i want show progressbar during this process. so how can i decide max value and increment value for progrssbar.
januar 22nd, 2011 at 09:47
I think there is a (little) mistake in your code :
while (dialog.getProgress()<= dialog.getMax()) {
must be : while (dialog.getProgress()< dialog.getMax()) {
If you don't, you will continuously send messages to the handler
Lin's
januar 22nd, 2011 at 09:48
And note you don’t have to use msg.recycle() in your handler :
http://groups.google.com/group/android-developers/browse_thread/thread/3859e96e99f00c17/556219b73e47123f
The handler will recycle message for you =D
Lin’s
marts 7th, 2011 at 21:46
Thanks so much for the code! I just wasted 5 hours working on a stupid progress bar!
juli 14th, 2011 at 03:59
How I do use the progress bar like ProgressDialog.STYLE_SPINNER???
I mean, when the dialog.getMax() is reached, the ProgressDialog still appears, unlike ProgressDialog.STYLE_HORIZONTAL…
august 10th, 2011 at 20:34
I need help with a progress dialogue that is trying to upload a http post I dont know when to implement the handler to call back to tell it that it has finished uploading and that it should dismiss.
Below is some sample code that I have.
// This is for the upload part
try{
//multipartentity
HttpResponse responsePOST = client.execute(httppost);
HttpEntity resEntity = responsePOST.getEntity();
InputStream inputstream = resEntity.getContent();
BufferedReader buffered = new BufferedReader(new InputStreamReader(inputstream));
StringBuilder stringbuilder = new StringBuilder();
String currentline = null;
while ((currentline = buffered.readLine()) != null)
{
stringbuilder.append(currentline + “\n”);
String result = stringbuilder.toString();
Log.v(“HTTP UPLOAD REQUEST”,result);
inputstream.close();
handler.sendMessage(handler.obtainMessage());}
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(share.this, “Upload failed”, Toast.LENGTH_SHORT).show();
}
//This is for the handler part
Handler handler = new Handler (){
public void HandleMessage (Message msg){
dialog.dismiss();
}
};
});
It just continues to upload without it stopping. Can you please direct me in the right path? Thanks in advance to anyone