Android Progress Bar Example

A progress bar is a visual indication of an extended computer process such as a file download, file transfer or an application installation. In Android we have two types of progress bar, a spinning wheel or a horizontal bar.A spinning wheel is used when we don't know the length of the process and a horizontal bar for representing the progress of the current operation changing the length as the operation progresses.

You can also set the horizontal bar to represent an indeterminate mode by using the method setIndeterminate(true). Let's say you have a file download process from a remote server then you can set the progress bar to indeterminate until the connection is established and then set it to regular progress bar as the file download starts. In this example we will review how to use both the spinning wheel and the horizontal progress bar.

Android spinning wheel progress bar
Android horizontal progress bar
Android horizontal progress bar file download complete

Android Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.as400samplecode"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />
 <uses-permission android:name="android.permission.INTERNET" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Android String Resources - strings.xml

<resources>

    <string name="app_name">Progress Bar Tutorial</string>
    <string name="menu_settings">Settings</string>
    <string name="start">Start</string>
    <string name="stop">Stop</string>
    <string name="start_download">Start File Download</string>
    <string name="my_file">My Downloaded File</string>
    <string name="finished">Finished downloading&#8230;</string>

</resources>

Android Application main Layout - activity_main.xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent" android:layout_height="match_parent"
 xmlns:android="http://schemas.android.com/apk/res/android">

 <Button android:id="@+id/start" style="?android:attr/buttonStyleSmall"
  android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:layout_alignParentLeft="true" android:layout_alignParentTop="true"
  android:text="@string/start" />

 <Button android:id="@+id/stop" style="?android:attr/buttonStyleSmall"
  android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:layout_alignParentTop="true" android:layout_toRightOf="@id/start"
  android:text="@string/stop" />

 <ProgressBar android:id="@+id/progressBar1"
  android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:layout_alignParentTop="true" android:layout_toRightOf="@+id/stop" />

 <Button android:id="@+id/download" style="?android:attr/buttonStyleSmall"
  android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:layout_alignParentLeft="true" android:layout_below="@+id/start"
  android:text="@string/start_download" />

 <ProgressBar android:id="@+id/progressBar2"
  style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_below="@id/download" android:padding="5dp" />

 <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_below="@+id/progressBar2" android:contentDescription="@string/my_file" />

 <TextView android:id="@+id/textView1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_alignBottom="@+id/download"
  android:layout_toRightOf="@+id/download" android:text="@string/finished"
  android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Android Application Activity - MainActivity.java

package com.as400samplecode;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.BitmapFactory;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

 private ProgressBar progressBar1;
 private ProgressBar progressBar2;
 private String filepath = "MyFileStorage";
 private File directory;
 private TextView finished;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
        directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
  
        progressBar1 = (ProgressBar) findViewById(R.id.progressBar1);
        progressBar1.setVisibility(View.GONE);
        progressBar2 = (ProgressBar) findViewById(R.id.progressBar2);
        progressBar2.setVisibility(View.GONE);
        finished = (TextView) findViewById(R.id.textView1);
        finished.setVisibility(View.GONE);
        
        Button start = (Button) findViewById(R.id.start);
  start.setOnClickListener(this);
  Button stop = (Button) findViewById(R.id.stop);
  stop.setOnClickListener(this);
  Button download = (Button) findViewById(R.id.download);
  download.setOnClickListener(this);
        
    }
    
    public void onClick(View v) {

  switch (v.getId()) {
  case R.id.start:
         progressBar1.setVisibility(View.VISIBLE);
   break;
   
  case R.id.stop:
         progressBar1.setVisibility(View.GONE);
   break;
   
  case R.id.download:
         String url = "http://upload.wikimedia.org/wikipedia/commons/0/05/Sna_large.png";
   grabURL(url); 
   break; 
   
   // More buttons go here (if any) ...

  }
 }
    
    public void grabURL(String url) {
  new GrabURL().execute(url);
 }
 
 private class GrabURL extends AsyncTask<String, Integer, String> {
  
  
  protected void onPreExecute() {
   progressBar2.setVisibility(View.VISIBLE);
         progressBar2.setProgress(0);
         finished.setVisibility(View.GONE);
         
     }

  protected String doInBackground(String... urls) {

   String filename = "MySampleFile.png";
   File myFile = new File(directory , filename);
   
   try {
             URL url = new URL(urls[0]);
             URLConnection connection = url.openConnection();
             connection.connect();
             int fileSize = connection.getContentLength();

             InputStream is = new BufferedInputStream(url.openStream());
             OutputStream os = new FileOutputStream(myFile);

             byte data[] = new byte[1024];
             long total = 0;
             int count;
             while ((count = is.read(data)) != -1) {
                 total += count;
                 publishProgress((int) (total * 100 / fileSize));
                 os.write(data, 0, count);
             }

             os.flush();
             os.close();
             is.close();
             
         } catch (Exception e) {
          e.printStackTrace();
         }

   return filename;
   
  }

  protected void onProgressUpdate(Integer... progress) {
   finished.setVisibility(View.VISIBLE);
   finished.setText(String.valueOf(progress[0]) + "%");
   progressBar2.setProgress(progress[0]);
     }
  
  protected void onCancelled() {
   Toast toast = Toast.makeText(getBaseContext(), 
     "Error connecting to Server", Toast.LENGTH_LONG);
   toast.setGravity(Gravity.TOP, 25, 400);
   toast.show();

  }

  protected void onPostExecute(String filename) {
   progressBar2.setProgress(100);
   finished.setVisibility(View.VISIBLE);
   finished.setText("Finished downloading...");
   File myFile = new File(directory , filename);
   ImageView myImage = (ImageView) findViewById(R.id.imageView1);
   myImage.setImageBitmap(BitmapFactory.decodeFile(myFile.getAbsolutePath()));
  }

 }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

References