Archive for January, 2012

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

, , , , , , , ,

18 Comments