Progress bar and downloading a file sample program in Android

By: Ashley Emailed: 1788 times Printed: 2623 times    

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>


Most Viewed Articles (in Android )

Latest Articles (in Android)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. I und. you guy's are using programming language to
View Tutorial          By: Ken at 2011-07-25 07:10:41

2. Perfect example and I have achieved my task. Thank
View Tutorial          By: Naeem Ahmad at 2011-08-18 05:34:54

3. i want to download in my assests folder what outpu
View Tutorial          By: korrupt koder at 2011-10-17 12:07:43

4. How to download more than one files. If I use for
View Tutorial          By: Riyas at 2012-01-08 07:55:03

5. Awesome code workings fro me thank you so much :)
View Tutorial          By: Shripad at 2012-01-24 08:58:03

6. I was able to modify this to work perfectly.

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

7. How to download any file when a button is in .jsp
View Tutorial          By: Gopesh at 2012-04-13 09:35:11

8. hi,thanks for the useful script..
keep publ

View Tutorial          By: vlganesh at 2012-06-14 18:20:33

9. This works great, just remember to add <uses-pe
View Tutorial          By: Nick at 2012-06-20 07:37:15

10. Does not work.
View Tutorial          By: Hallo at 2012-10-25 09:50:05

11. hi could u tell me how to download a file using se
View Tutorial          By: akki at 2013-02-19 05:52:03

12. hi in the above example u created a example for do
View Tutorial          By: akki at 2013-02-22 06:19:14

13. Hi there, a nice tutorial. i wanna ask, what about
View Tutorial          By: Alfa at 2013-03-06 04:04:26

14. very nice tutorial you can also check this one<
View Tutorial          By: pavan at 2013-05-06 13:04:53

15. im having problems with showDialog(int) who can i
View Tutorial          By: Samuel at 2013-06-30 05:13:38

16. just remember to add
<uses-permission an

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

17. How to download a pdf file from the server and sav
View Tutorial          By: harsha at 2013-08-12 07:52:22

18. nice help
View Tutorial          By: Akbar at 2014-06-11 12:44:23

19. This works perfect for me. The only big problem is
View Tutorial          By: Eric at 2014-11-20 03:49:19

20. How can I store a file in device internal memory a
View Tutorial          By: Fabio at 2014-11-20 11:25:41

21. Works like a charm for me ! but i stuck with an is
View Tutorial          By: santosh at 2014-12-17 12:44:09

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

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

23. Hello, this is working fine with jpg file. But I w
View Tutorial          By: Ray at 2015-09-01 04:18:00

24. Worked for me... I m thankful to the author
View Tutorial          By: Ashok Bhetwal at 2016-03-17 07:10:47

25. how to download .pdf file and store it in to parti
View Tutorial          By: ajay at 2016-05-21 06:23:48

26. Plz clarify what is the alternative code for showD
View Tutorial          By: buvana at 2016-12-23 10:31:55

27. JasonNix
View Tutorial          By: JasonNix at 2017-03-12 04:56:15

28. GLSGuacync
View Tutorial          By: GLSGuacync at 2017-04-06 09:36:25

29. JasonNix
View Tutorial          By: JasonNix at 2017-04-11 17:38:19

30. ThomasDix
View Tutorial          By: ThomasDix at 2017-04-20 18:20:45

31. JasonNix
View Tutorial          By: JasonNix at 2017-04-24 09:54:03

32. JasonNix
View Tutorial          By: JasonNix at 2017-04-25 09:11:44

33. Apboxymn
View Tutorial          By: Apboxymn at 2017-05-21 20:34:33

34. AUTOnelf
View Tutorial          By: AUTOnelf at 2017-05-25 19:16:57

35. Apboxymn
View Tutorial          By: Apboxymn at 2017-05-30 05:08:39

36. Dentro de 30 com maro a 1846, cumprimentos a Cidad
View Tutorial          By: PASSEIOS NO RIO DE JANEIRO COM CHUVA at 2017-07-19 08:21:44

37. What's up, always i used to check blog posts here
View Tutorial          By: Luxury strip club Barcelona at 2017-08-09 14:00:52

38. usefaniyaonih
View Tutorial          By: usefaniyaonih at 2017-08-13 00:49:24

39. etayismayi
View Tutorial          By: etayismayi at 2017-09-04 12:49:32