How to display Progress Bar in Android

In today’s tutorial we will learn how to display a ProgressBar in android application. If you are new to android development with no idea of what ProgressBar is all about I will suggest you first read android manual on ProgressBar.

There are many use cases for ProgressBar in android. But the main purpose is to communicate to a user that a task is running with an indication of how much work has been done and what is remaining to finish the task. ProgressBar is one of the numerous view controls that android for UI design.

Imagine a situation where an app downloads image from a remote source and you want the app users to know how the image download is progressing then a ProgressBar will come in handy.

Android provides a ProgressBar class that is use to create ProgressBar view in android application. We are going to learn how to use a ProgressBar and also an example of a ProgressBar in a real life android application.

Before we go further deep into the tutorial, I will like to emphasize that there is a difference between android ProgressBar and android ProgressDialog. If you are looking for a tutorial on android ProgressDialog then you can read the following tutorial on how to use ProgressDialog in android. One feature of android ProgressDialog is that it shows a kind of dialog that prevents a user from do any other thing until the progress is completed.

Android ProgressBar has so many properties that you can set. Some of these properties will help you to add a unique customization to your ProgressBar. Apart from the class properties, ProgressBar also contain many methods that play specific role when using a ProgressBar. Some of the methods are listed below.

getMax() – This methods returns the maximum value of the progress

incrementProgressBy(int diff) – This method increment the progress bar by the difference of value passed as a parameter

setIndeterminate(boolean indeterminate) – This method set the progress indicator as determinate or indeterminate

setMax(int max) – This method set the maximum value of the progress dialog

setProgress(int value) – This method is used to update the progress dialog with some specific value

show(Context context, CharSequence title, CharSequence message) – This is a static method , used to display progress dialog

The setMax() method of the ProgressBar class is use the set the maximum value of the progress. By default, the maximum value of a progress bar is 100. This can come in handy when you want to change the maximum progress value.

Another important thing to know is that you can make use of the indeterminate by setting the value to true. This is important when the length of task to be done is not known. The ProgressBar will automatically use the default spinning wheel as against the count indicator. If you wish to use a horizontal indicator rather than the default spinning wheel, you can use this style in your ProgressBar

style="?android:attr/progressBarStyleHorizontal"

You are free to experiment with some of the methods of the ProgressBar to understand what they do in details.

Enough of this explanation, right now, we will start by creating our new android project to demonstrate the use of ProgressBar in android application.

The first thing I will do is to list the environment and tools I will use in this tutorial but you are free to use whatever tools you are familiar with.

Windows XP

Eclipse (ADT)

Samsung Galaxy Fame Lite

Min SDK 8

Target SDK 19

There is no better time to start creating our application than now. To create a new android application project, following the steps as stipulated below.

How to create Android Application Project

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidProgressBar

Package: com.tutorial.androidProgressBar

Keep other default selections.

Continue to click on next button until Finish button is active

Then click on Finish Button

We will start by double clicking on our activity_main.xml layout to design the interface of our application. Once you have opened this file in your IDE, you can drag and drop a Textview control to your layout. Change the id of the Textview to progressinfo and center the view in your layout.

Drag and drop a button view control in your layout. Right click on the button view and change the id of the button to button_progressbar

Finally, drag and drop a progressbar view in your layout file. Change the name to progress_view.

Rather than doing all this process yourself, you can also choose to copy and paste the code below in your layout file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.androidprogressbar.MainActivity" >

    <TextView
        android:id="@+id/progressinfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="55dp"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button_progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/progressinfo"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp"
        android:text="@string/button_name" />

    <ProgressBar
        android:id="@+id/progress_view"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:indeterminate="false"
        android:max="100"
        android:minHeight="50dp"
        android:minWidth="200dp"
        android:progress="1"
        android:layout_centerVertical="true" />

</RelativeLayout>

Feel free to tweak the attributes of each view control in order to customize you UI interface the way it suits your application.

Now, we will go over to MainActivity.java. Double click on the file which is located in your project src folder. Once it is open, we will create all the instances of our view controls. This is done with Activity class method called findViewById(int id); Once we get all our object reference, we will attach a click event on the button view so that when the button is click, it will response to the click by doing a task that will be given to it.

We are going to create a new Thread because in android, time intensive tasks are run in a different thread so that they will not hang the main UI thread and cause the application to crash unprepared. The idea in this tutorial is to update the TextView control with the progress of the task that is running in a non-UI thread. For other threads to communicate or update the UI controls in the main thread, the main thread uses a Handler object to receive messages from other threads

You can delete all the codes in your MainActivity.java file. Copy and paste this code. Please make sure the package name conforms to your project package name.

package com.example.androidprogressbar;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

  private ProgressBar progressbar;
  private TextView updateProgressBar;
  private int progressCount;
  private Handler progressHandler = new Handler();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     progressbar = (ProgressBar) findViewById(R.id.progress_view);
     updateProgressBar = (TextView) findViewById(R.id.progressinfo);
     Button startProgressBar = (Button) findViewById(R.id.button_progressbar);

     startProgressBar.setOnClickListener(new OnClickListener() {

         @Override
         public void onClick(View arg0) {
           // TODO Auto-generated method stub
           new Thread(new Runnable() {
           @Override
           public void run() {
            // TODO Auto-generated method stub
            while (progressCount < 100) {
                progressCount += 2;
                progressHandler.post(new Runnable() {
                                                                                               @Override
               public void run() {
                 // TODO Auto-generated method stub
                 progressbar.setProgress(progressCount);
                 updateProgressBar.setText("Current Progress -"+ progressCount);
              }
           });
         }
       }

    }).start();
  }
});
}

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
   // Inflate the menu; this adds items to the action bar if it is present.
   getMenuInflater().inflate(R.menu.main, menu);
   return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
   // Handle action bar item clicks here. The action bar will
   // automatically handle clicks on the Home/Up button, so long
  // as you specify a parent activity in AndroidManifest.xml.
   int id = item.getItemId();
   if (id == R.id.action_settings) {
     return true;
   }
   return super.onOptionsItemSelected(item);
 }
}

In the code above, what we are trying to achieve is using a Handler to post progress update from non-UI thread and use the progress information to update some view controls in the UI thread. The Handler class uses its static method post which takes a Runnable as a parameter. The same process can also be achieved by using the handleMessage callback method of the Handler class as shown in the code snippet below.

package com.example.androidprogressbar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

   private ProgressBar progressbar;
   private TextView updateProgressBar;
   private int progressCount;
   private Handler progressHandler = new Handler();
      private static Handler progressbarHandler;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         progressbar = (ProgressBar) findViewById(R.id.progress_view);
         updateProgressBar = (TextView) findViewById(R.id.progressinfo);
         Button startProgressBar = (Button) findViewById(R.id.button_progressbar);
         startProgressBar.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View arg0) {
          // TODO Auto-generated method stub
          progressbarHandler = new Handler(){
          public void handleMessage(Message msg) {
             String passedProgress = msg.getData().getString("passed");
             if(null != passedProgress){
               progressbar.setProgress(progressCount);
               updateProgressBar.setText("Current Progress - " + progressCount);
          }
       }
    };
    new Thread(new Runnable() {
      @Override
      public void run() {
      // TODO Auto-generated method stub
      while (progressCount < 100) {
         try {
               Thread.sleep(500);
               progressCount += 2;
         } catch (InterruptedException e) {
           // TODO Auto-generated catch block
            e.printStackTrace();
         }                                                                                      
       Message currentProgress = progressbarHandler.obtainMessage();
       Bundle progressBundle = new Bundle();
       progressBundle.putString("passed", String.valueOf(progressCount));
       currentProgress.setData(progressBundle);
       progressbarHandler.sendMessage(currentProgress );
     }                                                                            }
  }).start();
 }
});
}

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
   // Handle action bar item clicks here. The action bar will
  // automatically handle clicks on the Home/Up button, so long
  // as you specify a parent activity in AndroidManifest.xml.
  int id = item.getItemId();
  if (id == R.id.action_settings) {
    return true;
  }
  return super.onOptionsItemSelected(item);
 } 
}

Moving Ahead

Finally, we will go deeper by creating a fresh android application that demonstrates how to implement ProgressBar when a remote image is downloaded. The process is basically the same expect that we are going to use an AsyncTask. If you are not familiar with AsyncTask in android, you can go through our tutorial on AsyncTask here.

So we will start by creating a new android project which we will call ProgressBarImageDownload. Following the initial steps we used to create the previous android project. Once you are done creating the project, you should open you activity_main.xml file located in the layout folder. Copy and paste the code below.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.progressbarimagedownload.MainActivity" >

    <ImageView
        android:id="@+id/download_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="89dp"
        android:contentDescription="@string/app_name" />

    <ProgressBar
        android:id="@+id/progress_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:indeterminate="true"
        android:max="100"
        android:minHeight="50dp"
        android:minWidth="200dp"
        android:progress="1"
        android:visibility="gone"
        android:layout_centerVertical="true" />

    <Button
        android:id="@+id/download_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="41dp"
        android:text="@string/button_name" />

</RelativeLayout>

What we have done above is to create three different types of view.

  1. The ImageView will be used to display the image we will download online
  2. The ProgressBar will indicate when the download button starts and stops with image download
  3. The Button view will be used to initiate image download online

There are other files that you will modify. Open strings.xml file located in your project values folder and copy and paste this line of code.

<string name=”button_name”>Download Image Online</string>

Since we are downloading image from a remote source, we are going to make use of internet permission so that our application can use internet. Open your project Manifest.xml file. Copy and paste the following code.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Finally, open your MainActivity.java file. Copy and paste the following code.

package com.example.progressbarimagedownload;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.support.v7.app.ActionBarActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class MainActivity extends ActionBarActivity {
 private ImageView downloadImage;
 private ProgressBar progressbar;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    downloadImage = (ImageView)findViewById(R.id.download_image);
    progressbar = (ProgressBar)findViewById(R.id.progress_view);
    Button downloadButton = (Button)findViewById(R.id.download_button);
    downloadButton.setOnClickListener(new OnClickListener(){
       String imagePath = "https://inducesmile.com/wp-content/uploads/2014/12/bg.jpg";
       @Override
       public void onClick(View arg0) {
          DownloadImageTask downloadImageTask = new DownloadImageTask();
          downloadImageTask.execute(imagePath);
       }
   });       
 }   

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap>{
        @Override
        protected Bitmap doInBackground(String... params) {
        // TODO Auto-generated method stub
        String getImageUrl = params[0];
        Bitmap externalDownloadImage = downloadImage(getImageUrl);
        return externalDownloadImage;
    }
   @Override
   protected void onPostExecute(Bitmap result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    progressbar.setVisibility(ProgressBar.GONE);
    if(null != result){
       downloadImage.setImageBitmap(result);
    }                                             
  }

  @Override
  protected void onPreExecute() {
   // TODO Auto-generated method stub
     super.onPreExecute();
     progressbar.setVisibility(ProgressBar.VISIBLE);
  }

 private Bitmap downloadImage(String imageUrl){
    Bitmap bitmap = null;
    URL downloadUrl;
    try {
         downloadUrl = new URL(imageUrl);
         URLConnection connection = downloadUrl.openConnection();
         connection.connect();
         InputStream is = connection.getInputStream();
         BufferedInputStream bis = new BufferedInputStream(is);
         bitmap = BitmapFactory.decodeStream(bis);
         bis.close();
     } catch (IOException e) {
        // TODO Auto-generated catch block
         Log.e("There is error getting the image from the server", e.getMessage());
     }                                             
      return bitmap;
   }                              
 }
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
     getMenuInflater().inflate(R.menu.main, menu);
     return true;
   }

   @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      int id = item.getItemId();
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
    }
}

That is it for this tutorial. If everything works out for you then this is the best time to run your application.

If you encounter any problem, kindly use our comment box to drop your questions or suggestions. You can also download all the source codes. If you are having difficulty downloading the code, you can drop your email address and the source codes will be forwarded to your inbox.

Don’t forget to subscribe with your email to get notify immediately a new post is published.

 

No Responses

Add a Comment