ATTENTION ATTENTION
gear.huuah.com has launched. Visit the shop at http://gear.huuah.com/. Lots of Photo Gear at the moment
ATTENTION ATTENTION
Itsplanned.com 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: itsplanned.com
Android Progress Bar and Thread updating
11.04.2010

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="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:
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.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);
        }
    };
}

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

  4. Vince Says:

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

  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?

    Cheers
    Arvind

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

    dialog.dismiss();
    }

    }

  10. js - huuah Says:

    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

  11. Arvind Says:

    Superb!

  12. Asma-ull-hosna Says:

    Hi,
    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:

    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.

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

    Lin's

  16. Lin's Says:

    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

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

Leave a Reply