Creating a Progress Dialog in Android:

It is a Dialog with a Progress wheel or bar. As it is an extension to AlertDialog, we can also add buttons also with in a Progress Dialog.

In this post, firstly I’ll explain how to create a Progress Dialog with a Progress Wheel and later with that of a Progress bar.

Just have a look at the screen shot of my activity which I’ve named ‘MyProgressDialog’.

The xml code for Xml layout is shown below:

<?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" >
     <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
     <Button
        android:id="@+id/btnpdring"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Progress Dialog with a ring" />
     <Button
        android:id="@+id/btnpdbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Progress Bar" />
 </LinearLayout>

Now, within the click event of the First Button, I’ve written the code for the Progress Dialog with a Progress Wheel(Spinning Ring).

Let’s have a look at the corresponding code.

final ProgressDialog myPd_ring=ProgressDialog.show(MyProgressDialog.this, "Please wait", "Loading please wait..", true);
                        myPd_ring.setCancelable(true);
                        new Thread(new Runnable() {  
                              @Override
                              public void run() {
                                    // TODO Auto-generated method stub
                                    try
                                    {
                                          Thread.sleep(5000);
                                    }catch(Exception e){}
                                    myPd_ring.dismiss();
                              }
                        }).start();

In order to display the Progress Dialog with a Spinning ring is as simple as calling the method ProgressDialog.show(MyProgressDialog.this, “Please wait”, “Loading please wait..”, true);

Where the first parameter is the Application Context, the second one is the Title Text, third is the Message text and fourth is whether the progress is Indeterminate. If we don’t want a Title text,  just leave the parameter as null string like this “ ”.

setCancelable(true) means the Dialog will be dismissed as we press the back button in the device.

Within a Thread I’ve called sleep(5000) method to make a delay of 5000ms.

Lastly I’ve called the dismiss() method inorder to dismiss the Progress Dialog. Here it will be dismissed after 5000ms.

This is how the Output looks like:

Now, let’s see how to create a Progress bar.

Before going into the code, let’s see what a Handler is. First the definition: A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue.

To process Message we need to Override the method handleMessage() and in our own thread that we create, we can send message using sendMessage() method or sendEmptyMessage() method.

Now, as you got an idea about the Handler, let’s move on to my code.

Here is my code:

Handler handle=new Handler(){
                  @Override
                  public void handleMessage(Message msg) {
                        // TODO Auto-generated method stub
                        super.handleMessage(msg);
                        myPd_bar.incrementProgressBy(5); //code to increment the progress by 5
                  }
            };

The handleMessage() method will process the message . Here, the code inside this method says that the Progress bar is incremented by 5.

For Updating the Progress bar, we need to use Threads and the code goes here:

new Thread(new Runnable() {                 
@Override
public void run() {
// TODO Auto-generated method stub
try
   {
    while(myPd_bar.getProgress()<=myPd_bar.getMax())
      {
           Thread.sleep(1000);
            handle.sendMessage(handle.obtainMessage());
     if(myPd_bar.getProgress()==myPd_bar.getMax())
      {
           myPd_bar.dismiss();
      }
      }
  }catch(Exception e){}
 }
 }).start();

Look at the above code, handle.sendMessage(handle.obtainMessage()) activates the Handler in which we’ve written the code for incrementing the Progress bar by 5 and sleep(1000) is used to delay the process by 1000ms. Now, we need to dismiss the Progress Dialog after  initial value progresses and reaches the maximum value.

The initial value is set as zero first and the maximum value is 30.

myPd_bar.setProgress(0);
myPd_bar.setMax(30);

The progress of the Progress bar progresses each time with an increment of 5 and as it reaches the maximum value, here it is 30, the progress is completed and the Dialog is dismissed using the method dismiss().

Now look at the screen shot below which shows a Progress bar:

 As the Progress reaches the Maximum value:

The Whole code is shown below:

package com.deepthi.progress;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
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.Toast;
 public class MyProgressDialog extends Activity {
    /** Called when the activity is first created. */
      Button pdring_btn,pdbar_btn;
      ProgressDialog myPd_bar;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        pdring_btn=(Button)findViewById(R.id.btnpdring);
        pdring_btn.setOnClickListener(new OnClickListener() {
                  @Override
                  public void onClick(View v) {
                        // TODO Auto-generated method stub
                        final ProgressDialog myPd_ring=ProgressDialog.show(MyProgressDialog.this, "Please wait", "Loading please wait..", true);
                        myPd_ring.setCancelable(true);
                        new Thread(new Runnable() {  
                              @Override
                              public void run() {
                                    // TODO Auto-generated method stub
                                    try
                                    {
                                          Thread.sleep(5000);
                                    }catch(Exception e){}
                                    myPd_ring.dismiss();
                              }
                        }).start();                                          
                  }
            });
      pdbar_btn=(Button)findViewById(R.id.btnpdbar);
      pdbar_btn.setOnClickListener(new OnClickListener() {
           @Override
            public void onClick(View v) {
                  // TODO Auto-generated method stub
                  myPd_bar=new ProgressDialog(MyProgressDialog.this);
                  myPd_bar.setMessage("Loading....");
                  myPd_bar.setTitle("Please Wait..");
                  myPd_bar.setProgressStyle(myPd_bar.STYLE_HORIZONTAL);
                  myPd_bar.setProgress(0);
                  myPd_bar.setMax(30);
                  myPd_bar.show();
                  new Thread(new Runnable() {
                       @Override
                        public void run() {
                              // TODO Auto-generated method stub
                              try
                              {
                                    while(myPd_bar.getProgress()<=myPd_bar.getMax())
                                    {
                                          Thread.sleep(1000);
                                          handle.sendMessage(handle.obtainMessage());
                                          if(myPd_bar.getProgress()==myPd_bar.getMax())
                                          {
                                                myPd_bar.dismiss();
                                          }
                                    }
                              }catch(Exception e){}
                        }
                  }).start(); 
            }
            Handler handle=new Handler(){
                  @Override
                  public void handleMessage(Message msg) {
                        // TODO Auto-generated method stub
                        super.handleMessage(msg);
                        myPd_bar.incrementProgressBy(5);
                  }
            };     
      });
    }
}
Advertisements

, , , , , , , ,

  1. #1 by Luke Acosta on March 1, 2012 - 1:58 pm

    I’m still learning from you, as I’m improving myself. I certainly enjoy reading all that is written on your site.Keep the aarticles coming. I loved it!

    • #2 by Deepthi G on March 1, 2012 - 5:59 pm

      Hey
      Thanks a bunch 🙂 Keep Reading and I’ll keep posting 😀

    • #3 by Omid on November 30, 2012 - 2:16 am

      I have One problem.
      First Time the progress bar works fine. but second time, It stops and don’t do anything. I mean it will not disappear after 5 second.
      It seems that it cannot be recreated!!.
      What can I do?

      ProgressDialog progDialog =new ProgressDialog(this);
      progDialog.setMessage(“We are still working”);
      progDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

      Thread thread=new Thread(new Runnable() {
      @Override
      public void run() {
      try {
      Thread.sleep(5000);
      } catch (InterruptedException e) {
      }
      dialog.dismiss();
      }
      });
      dialog =progDialog;
      thread.start();

  2. #4 by Tony on May 11, 2012 - 12:30 pm

    Thanks a lot ya, for showing progress wheel for a new activity, i was searchiong like anything. finally u gave me the correct 1.

    • #5 by Deepthi G on May 13, 2012 - 3:44 pm

      Hi Tony,
      Thanks a lot..!!Really happy to hear that my post has been useful to useful to you.. Keep reading..:)

      • #6 by irfan khan on August 21, 2012 - 4:30 pm

        hi
        i want to progress bar in notification with showing percentage please help me

  3. #7 by Stephany Cimmino on September 27, 2012 - 4:41 pm

    I will right away seize your rss as I can not in finding your e-mail subscription link or e-newsletter service. Do you’ve any? Please allow me recognise in order that I may subscribe. Thanks.

  4. #8 by Rashi.. Coorg.. on November 7, 2012 - 11:30 am

    Very nice one.. Thanks a lot.. 🙂

  5. #9 by venketesh on December 13, 2012 - 12:01 pm

    Hiiii
    Thanks for giving information clearly. I learned point to point.
    You have create so many apps in your bright feature.

  6. #10 by subarao on December 13, 2012 - 12:24 pm

    Very nicely superub…Thanks

  7. #11 by Andrea on April 6, 2013 - 11:31 pm

    Clean, clear code. I like that. Well done and Thanks!

  8. #12 by Hoàng Phan on April 12, 2013 - 1:06 am

    Thanks you so much…very useful to you….

  9. #13 by Timothy on April 15, 2013 - 2:37 am

    Thanks for this great piece of work. You made it look so simple.

  10. #14 by iphone repair on April 26, 2013 - 5:18 pm

    My partner and I stumbled over here different web page and
    thought I may as well check things out. I like what I see so now i’m following you. Look forward to looking into your web page for a second time.

  11. #15 by Raul on September 26, 2013 - 6:58 am

    Thanks por the contribution, this is such a great post! keep posting!

  12. #16 by rajani on March 11, 2014 - 10:45 pm

    Hi,
    I need to create a circular progress bar but it should not rotate like spinning one..I want a circular progress dialog it should start filling from 0% when we run it and have to end after 100%..could you please help me to create this..

  13. #17 by rajani r on March 11, 2014 - 10:53 pm

    Hi,
    I need to create a circular progress bar but it should not rotate like spinning one..I want a circular progress dialog it should start filling from 0% when we run it and have to end after 100%..could you please help me to create this..

  14. #18 by Rosa on March 15, 2014 - 2:21 pm

    I always used to study post in news papers but now as I am a user of
    internet so from now I am using net for articles, thanks to web.

  15. #19 by Luis Angel on November 27, 2014 - 4:24 am

    thanks, you post help me so good…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: