ATTENTION ATTENTION has launched. Visit the shop at Lots of Photo Gear at the moment
ATTENTION ATTENTION is just launched! - Task and project management made easy. Try it for free.

Create your own lists of things to do - arrange the order to do them - move them around - group them

No limitations - all free project management - try the free demo before signing up - demo:
Android Progress Bar and Thread updating

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:
Progress Bar Test Layout

XML layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

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


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:
Progress Bar Updating

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.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;

public class progressthread extends Activity implements OnClickListener {
    ProgressDialog dialog;
    int increment;
    public void onCreate(Bundle savedInstanceState) {
        Button startbtn = (Button) findViewById(;
    public void onClick(View view) { 
        // get the increment value from the text box
        EditText et = (EditText) findViewById(;
        // convert the text value to a integer
        increment = Integer.parseInt(et.getText().toString());
        dialog = new ProgressDialog(this);
        // set the progress to be horizontal
        // reset the bar to the default value of 0
        // get the maximum value
        EditText max = (EditText) findViewById(;
        // convert the text value to a integer
        int maximum = Integer.parseInt(max.getText().toString());
        // set the maximum value
        // display the progressbar;

        // 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

                       // active the update handler
               } catch (java.lang.InterruptedException e) {
                   // if something fails do something smart
        // start the background thread

    // handler for the background updating
    Handler progressHandler = new Handler() {
        public void handleMessage(Message msg) {

19 Responses to “Android Progress Bar and Thread updating”

  1. Vince Says:

    Hi, thanks for the great code. I use it in my project, but I get a NullPointerException at dialog.incrementProgressBy(1); Any ideas?

  2. js - huuah Says:

    Hello Vince. I cannot say why you are gettng a NullPointerException, without seeing a bit more of your code.

  3. Vince Says:

    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()) {

    ProgressDialog pdia = new ProgressDialog(this);

    Thread background = new Thread (new Runnable() {
    public void run()
    try {

    } catch (Exception e) {
    Log.e(“PH”, “S: Error”, e);





    Handler progressHandler = new Handler() {
    public void handleMessage(Message msg) {

    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?


  4. Vince Says:

    That might be useful too:
    E/AndroidRuntime( 1514): java.lang.NullPointerException
    E/AndroidRuntime( 1514): at proben.Proba$1.handleMessage(
    E/AndroidRuntime( 1514): at android.os.Handler.dispatchMessage(
    E/AndroidRuntime( 1514): at android.os.Looper.loop(
    E/AndroidRuntime( 1514): at
    E/AndroidRuntime( 1514): at java.lang.reflect.Method.invokeNative(NativeMethod)
    E/AndroidRuntime( 1514): at java.lang.reflect.Method.invoke(
    E/AndroidRuntime( 1514): at$
    E/AndroidRuntime( 1514): at
    E/AndroidRuntime( 1514): at dalvik.system.NativeStart.main(Native Method)

  5. Vince Says:

    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!

  6. js - huuah Says:

    That’s okay – glad you got it working :)

  7. Steven Says:

    Thanks a lot…all your code is helpfully for beinger like me………..Thanks alot once again….for such simple and easy code

  8. Arvind Says:

    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?


  9. Arvind Says:

    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) {
    if(dialog.getProgress()== dialog.getMax())



  10. js - huuah Says:


    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) {
                } else {

    Reference to the cancel() call:

    Reference to the dismiss() call:

  11. Arvind Says:


  12. Asma-ull-hosna Says:

    How could I create a progress bar to measure time of different video clip’s streaming/playing/pause/finish time of video?

  13. rajeev Says:

    can any 1 gimme da progress dialog code on a new screen with out any click events

  14. Kapil Says:


    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.

  15. Lin's Says:

    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 ;-)


  16. Lin's Says:

    And note you don’t have to use msg.recycle() in your handler :

    The handler will recycle message for you =D


  17. David Says:

    Thanks so much for the code! I just wasted 5 hours working on a stupid progress bar!

  18. Rommy Says:

    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…

  19. apapatp Says:

    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

    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);
    catch (Exception e) {
    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){

    It just continues to upload without it stopping. Can you please direct me in the right path? Thanks in advance to anyone

Leave a Reply