When our application does a task that takes a considerable amount of time, it is common sense to show the progress of the task to the user.
This is a good User Experience practice. In this tutorial i will be discussing the implementation of a process-progress dialog.

As an example, i am displaying a progress bar that runs while the app downloads an image from the web. And once the image is downloaded
completely i am showing the image in a image view. You could modify this example and try it with any file type you may wish. That could be fun!

Download Code

Creating new Project

1. Create a new project and fill all the details. File ⇒ New ⇒ Android Project
2. Open your main.xml are create a button to show download progress bar. Also define a ImageView to show downloaded image. Paste the following code in your main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- Download Button -->
    <Button android:id="@+id/btnProgressBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download File with Progress Bar"
        android:layout_marginTop="50dip"/>

    <!-- Image view to show image after downloading -->
    <ImageView android:id="@+id/my_image"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

3. Now in your main activity class import necessary classes and buttons. I am starting a new asynctask to download the file after clicking on show progress bar button.

public class AndroidDownloadFileByProgressBarActivity extends Activity {

	// button to show progress dialog
	Button btnShowProgress

	// Progress Dialog
	private ProgressDialog pDialog;

	// Progress dialog type (0 - for Horizontal progress bar)
	public static final int progress_bar_type = 0; 

	// File url to download
	private static String file_url = "https://api.androidhive.info/progressdialog/hive.jpg";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// show progress bar button
		btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
		// Image view to show image after downloading
		my_image = (ImageView) findViewById(R.id.my_image);

		/**
		 * Show Progress bar click event
		 * */
		btnShowProgress.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// starting new Async Task
				new DownloadFileFromURL().execute(file_url);
			}
		});
	}

4. Progress Dialog can be shown using ProgressDialog class. It is a subclass of normal AlertDialog class. So add an alert method in your main activity class.

    /**
	 * Showing Dialog
	 * */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case progress_bar_type:
			pDialog = new ProgressDialog(this);
			pDialog.setMessage("Downloading file. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setMax(100);
			pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pDialog.setCancelable(true);
			pDialog.show();
			return pDialog;
		default:
			return null;
		}
	}

5. Now we need to add our Async Background thread to download file from url. In your main activity add a asynctask class and name it as DownloadFileFromURL(). After downloading image from the web i am reading the downloaded image from the sdcard and displaying in a imageview.

	/**
	 * Background Async Task to download file
	 * */
	class DownloadFileFromURL extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread
		 * Show Progress Bar Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showDialog(progress_bar_type);
		}

		/**
		 * Downloading file in background thread
		 * */
		@Override
		protected String doInBackground(String... f_url) {
			int count;
	        try {
	            URL url = new URL(f_url[0]);
	            URLConnection conection = url.openConnection();
	            conection.connect();
	            // getting file length
	            int lenghtOfFile = conection.getContentLength();

	            // input stream to read file - with 8k buffer
	            InputStream input = new BufferedInputStream(url.openStream(), 8192);

	            // Output stream to write file
	            OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

	            byte data[] = new byte[1024];

	            long total = 0;

	            while ((count = input.read(data)) != -1) {
	                total += count;
	                // publishing the progress....
	                // After this onProgressUpdate will be called
	                publishProgress(""+(int)((total*100)/lenghtOfFile));

	                // writing data to file
	                output.write(data, 0, count);
	            }

	            // flushing output
	            output.flush();

	            // closing streams
	            output.close();
	            input.close();

	        } catch (Exception e) {
	        	Log.e("Error: ", e.getMessage());
	        }

	        return null;
		}

		/**
		 * Updating progress bar
		 * */
		protected void onProgressUpdate(String... progress) {
			// setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
       }

		/**
		 * After completing background task
		 * Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after the file was downloaded
			dismissDialog(progress_bar_type);

			// Displaying downloaded image into image view
			// Reading image path from sdcard
			String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
			// setting downloaded into image view
			my_image.setImageDrawable(Drawable.createFromPath(imagePath));
		}

	}

6. Open your AndroidManifest.xml file and add internet connect permission and writing to sdcard permission.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidhive"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AndroidDownloadFileByProgressBarActivity"
            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>

    <!-- Permission: Allow Connect to Internet -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Permission: Writing to SDCard -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

</manifest>

7. Run your Application and click on show progress bar button to see your progress bar. You can see the downloaded image in imageView once it is downloaded.

android download file and showing progress bar

Final Code

package com.example.androidhive;

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.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class AndroidDownloadFileByProgressBarActivity extends Activity {

	// button to show progress dialog
	Button btnShowProgress;

	// Progress Dialog
	private ProgressDialog pDialog;
	ImageView my_image;
	// Progress dialog type (0 - for Horizontal progress bar)
	public static final int progress_bar_type = 0; 

	// File url to download
	private static String file_url = "https://api.androidhive.info/progressdialog/hive.jpg";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// show progress bar button
		btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
		// Image view to show image after downloading
		my_image = (ImageView) findViewById(R.id.my_image);
		/**
		 * Show Progress bar click event
		 * */
		btnShowProgress.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// starting new Async Task
				new DownloadFileFromURL().execute(file_url);
			}
		});
	}

	/**
	 * Showing Dialog
	 * */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case progress_bar_type: // we set this to 0
			pDialog = new ProgressDialog(this);
			pDialog.setMessage("Downloading file. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setMax(100);
			pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pDialog.setCancelable(true);
			pDialog.show();
			return pDialog;
		default:
			return null;
		}
	}

	/**
	 * Background Async Task to download file
	 * */
	class DownloadFileFromURL extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread
		 * Show Progress Bar Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showDialog(progress_bar_type);
		}

		/**
		 * Downloading file in background thread
		 * */
		@Override
		protected String doInBackground(String... f_url) {
			int count;
	        try {
	            URL url = new URL(f_url[0]);
	            URLConnection conection = url.openConnection();
	            conection.connect();
	            // this will be useful so that you can show a tipical 0-100% progress bar
	            int lenghtOfFile = conection.getContentLength();

	            // download the file
	            InputStream input = new BufferedInputStream(url.openStream(), 8192);

	            // Output stream
	            OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

	            byte data[] = new byte[1024];

	            long total = 0;

	            while ((count = input.read(data)) != -1) {
	                total += count;
	                // publishing the progress....
	                // After this onProgressUpdate will be called
	                publishProgress(""+(int)((total*100)/lenghtOfFile));

	                // writing data to file
	                output.write(data, 0, count);
	            }

	            // flushing output
	            output.flush();

	            // closing streams
	            output.close();
	            input.close();

	        } catch (Exception e) {
	        	Log.e("Error: ", e.getMessage());
	        }

	        return null;
		}

		/**
		 * Updating progress bar
		 * */
		protected void onProgressUpdate(String... progress) {
			// setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
       }

		/**
		 * After completing background task
		 * Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after the file was downloaded
			dismissDialog(progress_bar_type);

			// Displaying downloaded image into image view
			// Reading image path from sdcard
			String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
			// setting downloaded into image view
			my_image.setImageDrawable(Drawable.createFromPath(imagePath));
		}

	}
}
This image is for thumbnail purpose
android download file by showing progress bar
Subscribe
Notify of
guest
146 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
tekin kara
tekin kara
7 years ago

i down load project and a run it. i got an error. “sdcard/downloadedfie.jpg” (permission denied)

Ashish Agrawal
Ashish Agrawal
7 years ago

I need help. Please contact me
ash.2412@yahoo.in

Sanjeev Dahiya
Sanjeev Dahiya
7 years ago

Why I’m not able to run this downloaded project in my System. It shows Error:(4491): /sdcard/downloadedfile.jpg (Permission denied) !!
Please help me out with this problem !!

VenomVendor
7 years ago
Reply to  Sanjeev Dahiya

try adding these permissions
android.permission.WRITE_INTERNAL_STORAGE
android.permission.WRITE_EXTERNAL_STORAGE

Sanjeev Dahiya
Sanjeev Dahiya
7 years ago
Reply to  VenomVendor

These 2 permissions are already there in my manifest file !!
But still I got this error !

VenomVendor
7 years ago
Reply to  Sanjeev Dahiya

r u getting error in real device or emulator.
In both the cases u have to add external sdcard manually.

Ankush Minda
Ankush Minda
7 years ago

I want to download an apk file from my server and after downloading i want it to run. Please tell me how can i do this.

Sagar Maiyad
Sagar Maiyad
7 years ago

hii Ravi, how can achieve this thing using ksoap web services..??

sneha
sneha
7 years ago

dismissDialog method is deprecated. Now what to use instead of that

chandu
chandu
7 years ago

hi
i want to display progress with spinner style and transparent background

can u please tell me

manish singh
manish singh
7 years ago

how to download file from server and save it on internal memory of android…

Bima Laksana Putra
Bima Laksana Putra
7 years ago

it’s great Tutorial, but I want to know. How to view image if file image on SDCard is exist and hidden the button download

suresh
suresh
7 years ago

Its really great tutorial. Thank u… 🙂

Deepak Kanyan
Deepak Kanyan
7 years ago

great TutoriaL…………..Gracias !!!!!!

Bunny
Bunny
7 years ago

Hi,
Thank you for the tutorial. But my progress bar is not working. What should I do for it?

Naveen
Naveen
7 years ago

Hi I am following this tutorial for download pdf file except the image. The prgress bar is there everything is fine only my file is getting corrupt…..!!please help me for that

Arju
Arju
7 years ago

Hi when i try to download for the second file(another file) it doesnt gets update..stays at 0 and dismisses when dialog completes..Actually 2nd time the size of my file becomes -1.. Can u pls help me out??

Sergio
Sergio
6 years ago
Reply to  Arju

int lenghtOfFile = conection.getContentLength(); does not always gives a result, it depens on the server. if you know the file size set the “lenghtOfFile” value explicitly. it happened to me when i was trying to download a file from google drive

Hanh Jay
Hanh Jay
4 years ago
Reply to  Arju

Excute() with multiple files like this, example with 3 files:
private static String file_url = “http:/….”;
private static String file2_url = “http:/….”;
private static String file3_url = “http:/….”;

new DownloadFileFromURL().execute(file_url, file2_url, file3_url);

URL url = new URL(f_url[0]);
URL url2 = new URL(f_url[1]);
URL url3 = new URL(f_url[2]);

so on…

Arju
Arju
7 years ago

Hi when i try to download for the second time(another file) it doesnt gets updated..stays at 0 and dismisses when download completes..Actually 2nd time the size of my file becomes -1.. Can u pls help me out??

mohammad
mohammad
7 years ago
Reply to  Arju

Hi,i have this problem too, please help me.

Hanh Jay
Hanh Jay
4 years ago
Reply to  mohammad

Excute() with multiple files like this, example with 3 files:
private static String file_url = “http:/….”;
private static String file2_url = “http:/….”;
private static String file3_url = “http:/….”;

new DownloadFileFromURL().execute(file_url, file2_url, file3_url);

URL url = new URL(f_url[0]);
URL url2 = new URL(f_url[1]);
URL url3 = new URL(f_url[2]);

continue with another things: input, output, data, count, total….

Gopal
Gopal
4 years ago
Reply to  Hanh Jay

@Hanh Jay, Can u pls explain me briefly? Because i’m trying to download 3 different files. How to continue with other things???

Shivansh
Shivansh
7 years ago

The Tutorial is good, but i have one more question about how to hide file from media scanner and creating .nomedia file and using them as source to imageview, please help on this matter.

thanks in advance…

Shivansh
Shivansh
7 years ago
Reply to  Shivansh

Thanks, i got the solution, by just adding extension to code like “downloadedFile.nomedia” worked, thumbs up Ravi, keep doing this cool stuff.

Arjun
Arjun
6 years ago

Was working fine..but unexpectedly one day it started giving this error.Please help :

06-05 11:56:41.466: W/System.err(14772): java.net.ProtocolException: Unexpected status line:

06-05 11:56:41.469: W/System.err(14772): at com.android.okhttp.internal.http.RawHeaders.setStatusLine(RawHeaders.java:108)

06-05 11:56:41.472: W/System.err(14772): at com.android.okhttp.internal.http.RawHeaders.fromBytes(RawHeaders.java:308)

06-05 11:56:41.473: W/System.err(14772): at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:135)

06-05 11:56:41.473: W/System.err(14772): at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:644)

06-05 11:56:41.475: W/System.err(14772): at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:347)

06-05 11:56:41.476: W/System.err(14772): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)

06-05 11:56:41.476: W/System.err(14772): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)

06-05 11:56:41.477: W/System.err(14772): at java.net.URL.openStream(URL.java:470)

06-05 11:56:41.477: W/System.err(14772): at com.gizmeon.skooltracking.Newsletter$load.doInBackground(Newsletter.java:418)

06-05 11:56:41.478: W/System.err(14772): at com.gizmeon.skooltracking.Newsletter$load.doInBackground(Newsletter.java:1)

06-05 11:56:41.479: W/System.err(14772): at android.os.AsyncTask$2.call(AsyncTask.java:288)

06-05 11:56:41.480: W/System.err(14772): at java.util.concurrent.FutureTask.run(FutureTask.java:237)

06-05 11:56:41.481: W/System.err(14772): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)

06-05 11:56:41.482: W/System.err(14772): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

06-05 11:56:41.482: W/System.err(14772): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

06-05 11:56:41.483: W/System.err(14772): at java.lang.Thread.run(Thread.java:841)

Sebastian Rank
Sebastian Rank
6 years ago

Ravi Tamada nice tutorial. Can you make a tutorial with progressbar where i saving a image for example from the camera?

Anuj
Anuj
6 years ago

Awesome tutorial. I tried lot of examples given on different websites but this is clearly understood.

aaa
aaa
6 years ago

Where is `showDialog()` method?

Sabri
Sabri
6 years ago

Thank you man! Awesome!

Huy Nguyễn Hữu
Huy Nguyễn Hữu
6 years ago

Very nice , thank so much 🙂

kprime
kprime
6 years ago

Perfect!! thank you!!!

victoria
victoria
6 years ago

thank you so much… you’re code is the only code that work with me

Anggrayudi H
Anggrayudi H
6 years ago

Hi, how to cancel the download?

babyskill
babyskill
6 years ago

Its not work on Android 13 And Smaller

theboom
theboom
6 years ago

You’re forgetten to declare my_image !

Silos
Silos
6 years ago

Dear Ravi

How to download with this method multiple files with mask: “*.csv” from external http server one by one to internal directory Android 4.x device ?

sd vipeen
sd vipeen
6 years ago

When i try the same tutorial using a word document, am able to download it but cant view it fr unknown reasons. And am able to store it only in my phone memory instead of sdcard.
Any suggestions.?

Rahul
Rahul
6 years ago

Your codes are suprb! Thank you so much!

Sunil Singh Chaudhary
Sunil Singh Chaudhary
6 years ago

little bit problem when without download show into imageview any help

learn shanky
learn shanky
5 years ago

Facing problem while downloading the source code….

Alok Verma
Alok Verma
5 years ago

How to create hidden folder and save file in that folder, so that the file is not visible to user.

Alok Verma
Alok Verma
5 years ago

Hi,
how to display progress bar in notifications while downloading a file

Nadim Matoussi
Nadim Matoussi
5 years ago

Thank you for the example
Does this apply on every file type (the download part) t
thankou you

neeko
neeko
5 years ago

how to download pdf guys..Thank you in advance..

Prince
Prince
4 years ago
Reply to  neeko

Just change the extension to .pdf
like make a folder named pdf

File folder = new File(Environment.getExternalStorageDirectory() + File.separator +”pdf/”);
if(!folder.exists())

{
folder.mkdirs();
Log.d(“SDcard”, “Folder created”);
}
// Output stream
OutputStream output = new FileOutputStream(“/sdcard/pdf/downloadedfile.pdf”);

byte data[] = new byte[1024];

THEMBO CHARLES LWANGA
THEMBO CHARLES LWANGA
5 years ago

Thank u sir

Hari
Hari
5 years ago

thanks for the example what is this 8192 and1024 explain in deail

i want to download json files from web server which are about 50 to 100kb of size

jacob taylor
jacob taylor
5 years ago

Hi,
Your codes are awesome and it is working properly.Thank you so much !

Ravi Tamada
5 years ago
Reply to  jacob taylor

You are welcome 🙂

Elizabeth Turner
Elizabeth Turner
5 years ago

WOW !
I have implemented the codes it is very useful .Actually the comments for this line is missing so it is little bit confusing..
btnShowProgress.setOnClickListener(new View.OnClickListener()

Muhammad Abuchaker
Muhammad Abuchaker
5 years ago

Got an Error : /sdcard/downloadedfile.jpg: open failed: EACCES (Permission denied).
Although i have set the permissions to write external and internal storage in the Android manifest.
Im using the android 6.0 NexusP emulator with 1GB size on disk.

basanta kumar
basanta kumar
5 years ago

Thanks Ravi for your Support…

Ravi Tamada
5 years ago
Reply to  basanta kumar

You are welcome 🙂

Shujhal Singh
Shujhal Singh
5 years ago
Reply to  Ravi Tamada

I am creating an android mobile application in which user can upload his/her resume and which can be then sent to the server.

Resume can be in pdf form or word form.

How to browse for the pdf and word files, which type should be given to browse and upload these files? like for images we have image.

@rpit Patel
@rpit Patel
5 years ago

when i use other url it’s work perfectly but when i upload file in our server and pass that link so it stuck into zero.I am getting minus value of progressbar in log cat and what is the problem i can’t understand please help me.

Tanvi Android Developer
Tanvi Android Developer
3 years ago
Reply to  @rpit Patel

Hello,
Did you get any solution for this?
I am getting the same issue.

Reason is, following statement
int lenghtOfFile = conection.getContentLength();
return -1

Please let me know if any solution.
Thank you

Bishal
Bishal
3 years ago

i also found this type of error ,then i found from url which i got is not correct so pls first u go through ur url which u got and run it in chrome browser if that url content come then its correct i dont think that url is correct which u got.

Tanvi Android Developer
Tanvi Android Developer
3 years ago
Reply to  Bishal

Thank you.

Issue was in url.

Manoj
Manoj
5 years ago

Hi Ravi,
Can You Create a New Tutorial with DialogFragment or Update this one as OnCreateDialog,showDialog etc were deprecated few years ago.ThankYou

Suhail Parvez
Suhail Parvez
4 years ago

How do i store a PDF file by using a URL instead of an Image. I wanted to store it in the internal memory of the app. But not the sd card ( as SD card might or might not be present on the user’s phone ).
Every application got it’s own “private” storage on the device, which means no-one else except your application can access this folder. How do i store it here and retrieve the PDF to display it.

gohil
gohil
4 years ago

thanks

gohil
gohil
4 years ago

dear brother
Ravi Tamada
All code is very best As Well AS it Workig
but i Ask you how to download Mp4 videos
please bro responces
my email id is gohilvipul025@gamil.com

Rehan.CH.
Rehan.CH.
4 years ago
Reply to  gohil

i also face the same issue please help me at chrehansarwar@gmail.com

Kristiana Jorgo
Kristiana Jorgo
4 years ago
Reply to  gohil

Did you solve it?

lordgodgiven
lordgodgiven
4 years ago

Hello,

I’d like to download image form my xampp server and store it in my sdcard with asyncHttClient library. Any idea?
Thanks

Nimmagadda Gowtham
Nimmagadda Gowtham
4 years ago

Here in this example we have DB Operation or some other Task in a private class included in our Activity. What if we want to write a class that can be used in common for all the DB Operations in out Android App ?
In other words how to get Progress Dialog when we have Async Task class outside our Activity ?

Rehan.CH.
Rehan.CH.
4 years ago

I want to download the file when first time click otherwise simply load downloaded file

146
0
Would love your thoughts, please comment.x
()
x