Programming Tutorials

Progress bar and downloading a file sample program in Android

By: Ashley in Android Tutorials on 2011-07-03  

This sample android program shows you how to show Progress Bar in Android. In this program many concepts are explained. A button is shown and when clicked, a big file is downloaded from flickr. The downloaded file is saved to the sdcard in the android phone. While the download is still in progress, a progress bar is shown with the actual percentage of download. So the code below explains, downloading a file from a server, saving a file to the sdcard and showing a progress bar all in one android program.

The download.java file is as follows:

package com.javasamples;

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

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class download extends Activity {
   
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startBtn = (Button)findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                startDownload();
            }
        });
    }

    private void startDownload() {
        String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
        new DownloadFileAsync().execute(url);
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage("Downloading file..");
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
        }
    }

class DownloadFileAsync extends AsyncTask<String, String, String> {
   
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		showDialog(DIALOG_DOWNLOAD_PROGRESS);
	}

	@Override
	protected String doInBackground(String... aurl) {
		int count;

	try {

	URL url = new URL(aurl[0]);
	URLConnection conexion = url.openConnection();
	conexion.connect();

	int lenghtOfFile = conexion.getContentLength();
	Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

	InputStream input = new BufferedInputStream(url.openStream());
	OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");

	byte data[] = new byte[1024];

	long total = 0;

		while ((count = input.read(data)) != -1) {
			total += count;
			publishProgress(""+(int)((total*100)/lenghtOfFile));
			output.write(data, 0, count);
		}

		output.flush();
		output.close();
		input.close();
	} catch (Exception e) {}
	return null;

	}
	protected void onProgressUpdate(String... progress) {
		 Log.d("ANDRO_ASYNC",progress[0]);
		 mProgressDialog.setProgress(Integer.parseInt(progress[0]));
	}

	@Override
	protected void onPostExecute(String unused) {
		dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
	}
}
}

The output of this program will be as shown in the android emulator below.

The main.xml file in your res/layout folder is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<TextView
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="@string/hello" />
	<Button
		android:text="Start long running task.."
		android:id="@+id/startBtn"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
	</Button>
</LinearLayout>







Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Android )

adb.exe: no devices/emulators found

Gradle, npm, react-native - How are they related?

Performing Streamed Install adb: failed to install app buildoutputsapkdebugapp-debug.apk: Exception occurred while executing 'install': android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space

Get Location of an android phone programmatically

Progress bar and downloading a file sample program in Android

Reading and Writing a file to SD card sample program in Android

Reading a file sample program in Android

'adb' is not recognized as an internal or external command, operable program or batch file.

Solution to error: unable to open connection to server due to security error

Emulator: WARNING | *** No gRPC protection active, consider launching with the -grpc-use-jwt flag.***

Android Emulator

Intent in Android to call one activity from another activity.

Emulator: glTexImage2D: got err pre :( 0x506 internal 0x8058 format 0x1908 type 0x1401

Gallery sample program in Android

GridView sample program in Android

Latest Articles (in Android)

Keep your android phone awake while debugging

compileSdkVersion vs buildToolsVersion in app/build.gradle

gradle build failed Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema

Gradle, npm, react-native - How are they related?

Emulator: glTexImage2D: got err pre :( 0x506 internal 0x8058 format 0x1908 type 0x1401

Emulator: WARNING | *** No gRPC protection active, consider launching with the -grpc-use-jwt flag.***

./gradlew assembleDebug '.' is not recognized as an internal or external command, operable program or batch file.

'adb' is not recognized as an internal or external command, operable program or batch file.

Performing Streamed Install adb: failed to install app buildoutputsapkdebugapp-debug.apk: Exception occurred while executing 'install': android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space

Is it safe to delete userdata-qemu.img userdata-qemu.img.qcow2 files

adb.exe: no devices/emulators found

How to start the Android emulator

Get Location of an android phone programmatically

Getting Started with Android

Solution to error: unable to open connection to server due to security error

Related Tutorials

Keep your android phone awake while debugging

compileSdkVersion vs buildToolsVersion in app/build.gradle

gradle build failed Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema

Gradle, npm, react-native - How are they related?

Emulator: glTexImage2D: got err pre :( 0x506 internal 0x8058 format 0x1908 type 0x1401

Emulator: WARNING | *** No gRPC protection active, consider launching with the -grpc-use-jwt flag.***

./gradlew assembleDebug '.' is not recognized as an internal or external command, operable program or batch file.

'adb' is not recognized as an internal or external command, operable program or batch file.

Performing Streamed Install adb: failed to install app buildoutputsapkdebugapp-debug.apk: Exception occurred while executing 'install': android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space

Is it safe to delete userdata-qemu.img userdata-qemu.img.qcow2 files

adb.exe: no devices/emulators found

How to start the Android emulator

Get Location of an android phone programmatically

Getting Started with Android

Solution to error: unable to open connection to server due to security error