Using threads and ProgressDialog


SDK Version: 
M5

This is a simple tutorial to show how to create a thread to do some work while displaying an indeterminate ProgressDialog. Click here to download the full source.

We'll calculate Pi to 800 digits while displaying the ProgressDialog. For the sake of this example I copied the "Pi" class from this site.

We start with a new Android project, only thing I needed to change was to give that TextView an id in main.xml so that I could update it in the Activity.

Because this Activity is so small I'll show you the whole thing and then discuss it at the end:

  1. public class ProgressDialogExample extends Activity implements Runnable {
  2.  
  3.         private String pi_string;
  4.         private TextView tv;
  5.         private ProgressDialog pd;
  6.  
  7.         @Override
  8.         public void onCreate(Bundle icicle) {
  9.                 super.onCreate(icicle);
  10.                 setContentView(R.layout.main);
  11.  
  12.                 tv = (TextView) this.findViewById(R.id.main);
  13.                 tv.setText("Press any key to start calculation");
  14.         }
  15.  
  16.         @Override
  17.         public boolean onKeyDown(int keyCode, KeyEvent event) {
  18.  
  19.                 pd = ProgressDialog.show(this, "Working..", "Calculating Pi", true,
  20.                                 false);
  21.  
  22.                 Thread thread = new Thread(this);
  23.                 thread.start();
  24.  
  25.                 return super.onKeyDown(keyCode, event);
  26.         }
  27.  
  28.         public void run() {
  29.                 pi_string = Pi.computePi(800).toString();
  30.                 handler.sendEmptyMessage(0);
  31.         }
  32.  
  33.         private Handler handler = new Handler() {
  34.                 @Override
  35.                 public void handleMessage(Message msg) {
  36.                         pd.dismiss();
  37.                         tv.setText(pi_string);
  38.  
  39.                 }
  40.         };
  41.  
  42. }

So we see that this Activity implements Runnable. This will allow us to create a run() function to create a thread.

In the onCreate() function on line 18 we find and initialize our TextView and set the text telling the user to press any key to start the computation.

When the user presses a key it will bring us to the onKeyDown() function on line 27. Here we create the ProgressDialog using the static ProgressDialog.show() function, and as a result the pd variable is initialized. We also create a new Thread using the current class as the Runnable object. When we run thread.start() a new thread will spawn and start executing the run() function.

In the run() function we calculate pi and save it to the String pi_string. Then we send an empty message to our Handler object on line 40.

Why use a Handler? We must use a Handler object because we cannot update most UI objects while in a separate thread. When we send a message to the Handler it will get saved into a queue and get executed by the UI thread as soon as possible.

When our Handler receives the message we can dismiss our ProgressDialog and update the TextView with the value of pi we calculated. It's that easy!

Comments

using threads and ProgressDialog

I needed to create a thread while displaying an indeterminate ProgressDialog. Your solution worked like a breeze. Ornela from
justhost review

The handler will not run in

The handler will not run in the UI thread and you will get an error if you do not create the instance of the new class in the UI thread. Acne Treatment Homepathic

So if you're not creating the

So if you're not creating the instance of the new class in the UI thread then the handler isn't running in the UI thread and you will have a problem.Thanks
Atlanta sex crimes attorney

hm..I downloaded This

hm..I downloaded This tutorial and it helped me a lot to learn how to create a thread to do some work while displaying an indeterminate Progress Dialog,also the thread shown in inage is very helpful. Thank you.
usa business directory

So if you're not creating the

So if you're not creating the instance of the new class in the UI thread then the handler isn't running in the UI thread and you will have a problem.

5S system

You have to use a Handler

You have to use a Handler object because you cannot update many UI objects while in another thread. Find Electrical Engineer Job Listings

If you're not familiar with

If you're not familiar with using additional threads with a Handler, see the example Activity below that uses a second thread to increment a progress dialog.
Head Shop

Yes but why activity is still

Yes but why activity is still the main thing to change anything with this process? I reckon that it could be done different way. And yes why the dialog is dismiss???

casino games

I´ve been doing some test,

I´ve been doing some test, and it seems it never enter here..
Commercial Roofing

The ProgressDialog display is

The ProgressDialog display is set always and we can make the thread to perform the needed job.
Life Insurance Quotes

if you're not creating the

if you're not creating the instance of the new class in the UI thread then the handler isn't running in the UI ..
french roulette layout

The ProgressDialog display is

The ProgressDialog display is set always and we can make the thread to perform the needed job. This is explained in detail with the help of Android project.
News and Entertainment, Sell and Buy

So if you're not creating the

So if you're not creating the instance of the new class in the UI thread then the handler isn't running in the UI thread and you will have a problem.
scooby doo games

It is Helpful

I downloaded This tutorial and it helped me a lot to learn how to create a thread to do some work while displaying an indeterminate ProgressDialog,also the thread shown in inage is very helpful. Thanks for the post.
Attache

Screen rotation and progress bar

After needing to use this in an app and needing some extra functionality and solving some problems I wrote an article on how I did it.

http://www.eigo.co.uk/Threads-and-Progress-Dialogs-in-Android-Screen-Orientation-Rotations.aspx

How to manage a thread and show the percentage complete in the progress dialog's progress bar, this solution allows you to keep the thread and progress dialog going even though screen rotations destroy the activity.

Thankyou sir. I always learn

Thankyou sir. I always learn new things in hellandroid. I would love to bookmark this site on my digg and tweet.
Logo Design

Does anyone know...

Does anyone know of a way to call a dialog box during onCreate()? If I put it in onClick() or something like that it works fine, but if I put it in onCreate() it shows the progressDialog from the home screen then renders the activity..
Internet Hosting save fuel reverse phone detective tava tea error fix

A dialog that shows a short

A dialog that shows a short message and a progress bar. Optionally, it can display an ABORT button.

Stock Market

A dialog showing a progress

A dialog showing a progress indicator and an optional text message or view. Only a text message or a view can be used at the same time.
motorcycle exhaust

cool

I think you are logically very strong.....you parents must be teacher or professor of college..... the codes which you wrote is awesome..... its working man......

Keep Going
vedic math blog

Here we create the

Here we create the ProgressDialog using the static progressDialog.show() function, and as a result the pd variable is initialized.
thanks Web Resources

Can anyone please tell me how

Can anyone please tell me how to call a dialog box during onCreate()? ... when I put it in onClick() or something like that it works fine , but when I put it in onCreate() it shows the progressDialog from the home screen then renders the activity..
Need a solve to this Error please .

Inflatable Party Rentals | Free arabic movies

The functions used here in

The functions used here in above article are nice but there should also some in the form of array and arranged for the ease of the program. white pages

onKeyDown() function on line

onKeyDown() function on line 27. Here we create the ProgressDialog using the static ProgressDialog.show() function, and as a result the pd variable is initialized.
moving checklist

I did

I did get it to run on 38

Driving Directions.
Peliculas Gratis
Traductores

Nice post !!!

I was searching for 'the process of creating thread' and this post provides the needed information and is very useful. The ProgressDialog display is set always and we can make the thread to perform the needed job. This is explained in detail with the help of Android project.
Dallas SEO

does it go away?

It looks like it never goes away!

J
Google For Driving Directions.

How can I cancel the

How can I cancel the computerizing thread when I cancel the progress dialog?

in onCreate()

Does anyone know of a way to call a dialog box during onCreate()? If I put it in onClick() or something like that it works fine, but if I put it in onCreate() it shows the progressDialog from the home screen then renders the activity..

Setup a Handler and send a

Setup a Handler and send a message to the Handler in onCreate() and then have the Handler launch the dialog. I'm pretty sure that works..

cancel the thread ?

How can I cancel the computerizing thread when I cancel the progress dialog?

Depends what the thread is

Depends what the thread is doing, see this doc:

http://java.sun.com/j2se/1.4.2/docs/guide/misc/threadPrimitiveDeprecatio...

not working

I am trying this with a new class.. however it says Can't call handler inside the thread that has not called Looper.preapre().

Tryied to put Looper.prepare() in the calling thread.. but no use.

Could you explain what could be wrong here..

Regards,
Raja Nagendra Kumar
C.T.O
www.tejasoft.com

The handler runs in whatever

The handler runs in whatever thread created it. So if you're not creating the instance of the new class in the UI thread then the handler isn't running in the UI thread and you will have a problem.

It get to the run function

It get to the run function yes, but after that never goes to handleMessage function..

Thanks.

No the text does not change

No the text does not change at all.. I´ve been doing some test, and it seems it never enter here -->

public void handleMessage(Message msg) {
pd.dismiss();
tv.setText(pi_string);

}

Any idea?..

Does it ever get to the

Does it ever get to the run() function on 38?

Yes it get to the run

Yes it get to the run function..

Thanks but it´s not working

Thanks but it´s not working for me, I don´t see the dialog dismiss..

The dialog never goes away?

The dialog never goes away? Does the text view get set with the value?