Progress bar and downloading a file sample program in Android

By: Ashley Emailed: 1598 times Printed: 2042 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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>



Android Home | All Android Tutorials | Latest Android Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(19)


1. View Comment

I und. you guy's are using programming language to built this feature of progress bar. Well I'm a basic user so i don't know how to get this to work? or what can i do to this, please provide simple steps on how i can get this to work on my htc desire (android)?
Pls help


View Tutorial          By: Ken at 2011-07-25 07:10:41
2. View Comment

How to download more than one files. If I use for loop, progress bar is not displayed properly.

View Tutorial          By: Riyas at 2012-01-08 07:55:03
3. View Comment

Awesome code workings fro me thank you so much :)

View Tutorial          By: Shripad at 2012-01-24 08:58:03
4. View Comment

I was able to modify this to work perfectly.

The 'onProgressUpdate' was the key for me.


View Tutorial          By: _Jon at 2012-04-01 23:04:49
5. View Comment

How to download any file when a button is in .jsp and that jsp is loaded it in my android application as webView?

View Tutorial          By: Gopesh at 2012-04-13 09:35:11
6. View Comment

This works great, just remember to add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> to your permissions or else it will not work.

View Tutorial          By: Nick at 2012-06-20 07:37:15
7. View Comment

Does not work.

View Tutorial          By: Hallo at 2012-10-25 09:50:05
8. View Comment

hi could u tell me how to download a file using service in android with sample code

View Tutorial          By: akki at 2013-02-19 05:52:03
9. View Comment

hi in the above example u created a example for downloading file using activity but could u write a code for service for downloading a file using service class if possible

View Tutorial          By: akki at 2013-02-22 06:19:14
10. View Comment

Hi there, a nice tutorial. i wanna ask, what about uploading file?

with the same case with your post, but for uploading image. how to doing that?

i looking for it this whole day, but didn't find a good one. can u help me?


View Tutorial          By: Alfa at 2013-03-06 04:04:26
11. View Comment

im having problems with showDialog(int) who can i fix it?

View Tutorial          By: Samuel at 2013-06-30 05:13:38
12. View Comment

just remember to add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" >


View Tutorial          By: Mouad at 2013-07-22 10:47:27
13. View Comment

How to download a pdf file from the server and save it in sdcard.

View Tutorial          By: harsha at 2013-08-12 07:52:22
14. View Comment

nice help

View Tutorial          By: Akbar at 2014-06-11 12:44:23
15. View Comment

This works perfect for me. The only big problem is how to add a cancel download button. I know I have to use downloadManager #remove but , how can I implement that here .And also the back button doesnt work once the download starts. And help on how to move from here? Thanks

View Tutorial          By: Eric at 2014-11-20 03:49:19
16. View Comment

How can I store a file in device internal memory and not in SD card?

Thanks


View Tutorial          By: Fabio at 2014-11-20 11:25:41
17. View Comment

Works like a charm for me ! but i stuck with an issue that the alert dialogue not getting dismiss it is still visible after downloading the image. any help??

View Tutorial          By: santosh at 2014-12-17 12:44:09
18. View Comment

tnx.
i have problem why is that to slow???


View Tutorial          By: rozhin at 2015-08-21 07:54:42
19. View Comment

Hello, this is working fine with jpg file. But I want to show progress bar while downloading a pdf or doc file. For these, it is no working. What should I do? What changes in code should be made?

View Tutorial          By: Ray at 2015-09-01 04:18:00

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Ashley
Is autodiscover CNAME a must in Office 365
Directory Synchronization tool in Office 365
Configure Outlook Manually for Office 365
Review: Ruggear - The world's most Rugged Phone in Singapore
Solution to error: unable to open connection to server due to security error
Making your Alias email as 'Send As' in Office 365
Steps to Create Shared Mailbox in office 365
xxxx cannot be loaded because the execution of scripts is disabled on this system. Please see “get-help about_signing” for more details.
The user's Outlook Live mailbox is full.
Outlook Live couldn't connect to the IMAP server.
The user's mailbox has already been migrated.
An Outlook Live mailbox wasn't found for the user.
Outlook Live couldn't sign in to the user account on the IMAP messaging system.
Android Send SMS and Make a phone call in Android Application
Android Preferences - Using Preferences in Android Tutorial

More Tutorials in Android
Getting Started with Android
Solution to error: unable to open connection to server due to security error
Android Preferences - Using Preferences in Android Tutorial
Android Send SMS and Make a phone call in Android Application
Android Emulator
Intent in Android to call one activity from another activity.
Animation sample program in Android
Another Animation sample program in Android
ArrayAdapter sample program in Android
Spinner sample program in Android
GridView sample program in Android
Gallery sample program in Android
Date and Time sample program in Android
Progress bar and downloading a file sample program in Android
Reading a file sample program in Android

More Latest News
Most Viewed Articles (in Android )
Progress bar and downloading a file sample program in Android
Reading and Writing a file to SD card sample program in Android
Android Send SMS and Make a phone call in Android Application
Animation sample program in Android
ArrayAdapter sample program in Android
Intent in Android to call one activity from another activity.
Spinner sample program in Android
Reading a file sample program in Android
Solution to error: unable to open connection to server due to security error
Date and Time sample program in Android
GridView sample program in Android
Another Animation sample program in Android
Gallery sample program in Android
Android Emulator
Error generating R.java from manifest
Most Emailed Articles (in Android)
AlertDialog sample program in Android
Animation sample program in Android
Error generating R.java from manifest
Another Animation sample program in Android
ArrayAdapter sample program in Android
Spinner sample program in Android
GridView sample program in Android
Gallery sample program in Android
Date and Time sample program in Android
Progress bar and downloading a file sample program in Android
Reading a file sample program in Android
Reading and Writing a file to SD card sample program in Android
Intent in Android to call one activity from another activity.
Android Emulator
Android Preferences - Using Preferences in Android Tutorial