Android Download Files & Save - Androhub

Download Files Banner

Android Download Files & Save

In this tutorial we are going to learn how to download pdf, doc , video, mp3, zip ,etc. files from server and save them in device memory.

Below are certain things that we are going to learn in this tutorial :

 1. Download Files – Download Files from Server Url.

2. Save Files – Create Folder in device and save the dowloaded files.

3. Download Multiple Files – Download Many Files at a time.

VIDEO DEMO

1. Create a new project in Android Studio by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.

2. Open res=>values=strings.xml and add the following strings to it.

3. Create a xml layout naming activity_main.xml and add the following code. In this  layout there are some Buttons for showing downloading different type of files.

4. Create a Utils.java class and write all download urls here.

5. Create a CheckForSDCard.java class for checking if SDCard is present or not.

6. Now create a DownloadTask.java and add the following code. In this code AsyncTask is used for downloading data from server. There are several main steps in doInBackground(Void…arg0) that are listed below :

1. Converting download url into URL:

2. Opening Url Connection for data downloading:

3. Setting request method to server:

4. Connect the open connection:

5. Create a directory in SD Card if not present:

6. Create an Output file i.e. download file inside above created directory:

Note: Give extension to your outputFile like .pdf, .mp3, .mp4 etc.

7. Download File and write it over the outputFile created:

8. Close all connection after downloading:

Full Code of DownloadTask.java

7. Now create MainActivity.java and add the following code. In this code i am starting AsyncTask on button click.
But before downloading it is necessary there should be a proper internet connection. So for this I had created a method naming isInternetConnected() that will return true or false.

If you are new in how to detect internet connection then check Detect Internet Connection Tutorial.

Last Button is for Opening  downloaded folder and the code for opening download folder is below:

Full MainActivity.java Code

8. Finally come to AndroidManifest.xml file and add below several permissions to Manifest file.

9. Finally, all done you can use above steps for downloading any kind of files.

Thanks. :)

 

95 Comments

Arjun
Wednesday, May 24th, 2017

Not working. Shows IO Execption.

Dr. Droid
Wednesday, May 24th, 2017

Hi Arjun,

I think you are running code in Marshmallow API (6.0+) devices. So thats why its throwing exception. For this you need to take permissions during runtime. You can check below link to learn how to take permissions during runtime:
https://www.androhub.com/working-android-marshmallow-6-0-permissions/

Thanks

Kailas Bhakade
Tuesday, July 11th, 2017

It worked, Thanks. But if I want to make it generic for creation of file with extension then how i we do it. How can I get extension from url for create new file of the same name.

Dr. Droid
Tuesday, July 11th, 2017

Hi Kailas,

You can use below stackoverflow link to check which extension you are getting from url:
https://stackoverflow.com/questions/3234090/how-to-determine-the-file-extension-of-a-file-from-a-uri

Thanks

Juan Hernández
Thursday, July 20th, 2017

It is possible to show the percentage of download for each file?

Dr. Droid
Friday, July 21st, 2017

Hi Juan,

Please follow the below link to show percentage while downloading each file : https://www.androhub.com/android_progressbar/

Thanks

moh99
Friday, July 21st, 2017

Hi, Thank you for your nice Tutorial. I have a problem. When I click on download buttons, show Download failed and download again. I set Permissions in Android Manifest.

Dr. Droid
Friday, July 21st, 2017

Hi Moh99,

May be you are testing in Marshmallow+(API Level 6.0) Devices, in that devices you need to take runtime permissions. Please check the below link for help:
https://www.androhub.com/working-android-marshmallow-6-0-permissions/

Thanks

Zoraiz Ejaz
Monday, August 7th, 2017

Thanks. It worked. Downloaded files are store in internal storage but when i click on the downloaded folder to open all files are faded and i am unable to click on them.

Dr. Droid
Friday, August 11th, 2017

Hi Zoraiz,

Fading issue is basically may be your device issue or may be you don’t have permission to access those files. Please try to change the location.

Thanks

kishor singh
Tuesday, September 26th, 2017

Error in code. You are trying to update UI from doInBackground. Try to use RunonUiThread to show Toast.

Jagdish
Tuesday, October 10th, 2017

Dr Droid, Thanks so much, this was very useful.

@Kishor Singh, he is passing a context from the calling function which is being used while showing the Toast message, so there are no errors at runtime.

For those people who are seeing grayed out files here is what I did:
1. Modify the code to store the files in a Public Directory like ‘Download’ (in case you are ok sharing the file with other Apps) using the following call to get the location of the public directory:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
2. In phones like Nexus, browse the file using inbuilt application as follows: “Settings->Storage and USB->Explore->Download”. You will see the file without being grayed out.
Hope this helps.

Dr Droid, thanks once again for this wonderful website !!!

Lawrence
Tuesday, December 26th, 2017

Thanks a lot, worked however I have noticed it’s failing to download bigger files. It’s working on small size files less than 1mb but tried 3mb files and failed.

Michael
Saturday, March 17th, 2018

Thanks a lot! Amazing tutorial. It seems that adding request permissions in the manifest file isn’t enough to write in my external memory so i just wanted to add that I had to make a modification in the onClick method of the MainActivity Class before the switch case:

//Before starting any download check if write permissions are granted
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
Log.e(TAG , “WRITE EXTERNAL STORAGE PERMISSION NOT GRANTED”);
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
return;

}

rajesh bhimani
Thursday, May 3rd, 2018

good job sir.

all code work perfectly.

but is it possible to download files from google drive

thanks in andvance

Dr. Droid
Monday, May 7th, 2018

Hi Rajesh,

To access Google Drive you need to integrate with Driver API. Here is the link : https://developers.google.com/drive/android/

Thanks

sagar
Sunday, May 20th, 2018

working good but when i change the link of files with my own ,then it fails to download.only the file from ur link is working, other link is not downloading…my url is correct

Dr. Droid
Sunday, May 20th, 2018

Hi Sagar,

Please change the main url also : public static final String mainUrl = “https://androhub.com/demo/”;

Thanks

mind
Monday, May 28th, 2018

how toafter download file show listview file?
example file pdf
thanks

babang
Wednesday, May 30th, 2018

how to download all file in one folder?

Dr. Droid
Wednesday, May 30th, 2018

Hi Babang,

The above given code is already downloading all files in single directory only.

Thanks

PleaseHelpMe
Friday, June 1st, 2018

hey bro i have volley from herehttps://awsrh.blogspot.com/2018/03/volley-glide-tutorial-parse-json.html
how to make button in volley and download file each list view like google book?
https://imgur.com/a/ZN1sZUW
https://imgur.com/a/VHpuCPx

Dr. Droid
Friday, June 1st, 2018

Hi PleaseHelpMe,

You need to implement DownloadManager.

Please check this link : https://developer.android.com/reference/android/app/DownloadManager.

Thanks

PleaseHelpMe
Friday, June 1st, 2018

ok thanks

Jordi
Monday, June 11th, 2018

Hello bro
TextView tv2 = tv_file;
final String testing = tv2.getText().toString();

public static final String downloadPdfUrl = “”;

i have url from testing and want donwloadPdfUrl can read textview testing.
how to read from testing?

Dr. Droid
Tuesday, June 12th, 2018

Hi Jordi,

You can simply use : String downloadPdfUrl = testing;

Note : make sure you don’t use static and final with downloadPdfUrl.

Thanks

Jordi
Friday, June 15th, 2018

hello im new in android
how to downloadpdfurl not static?
i try and error
new DownloadTask(CatalogDetailActivity.this, DownloadPdf,Utils.downloadPdfUrl3);

mysourcecode:
https://gist.githubusercontent.com/nafsan1/96c2d05d943f8fb6ad94f1fdb0d076a4/raw/cd945a354183eae7b0c755e435064f6f82f55819/androhub.java

Dr. Droid
Saturday, June 16th, 2018

Hi Jordi,

You need to make some changes to the below lines:

public static String downloadDirectory = “Pdf Test”; //here you need to use your pdf file right now there is no extension to it. It
//should be pdf Test.pdf something like this.

public static String mainUrl = “https://androhub.com/demo/”; //And here you need to replace your domain url where the pdf file
//exist. Like http://example.com/path_of_the_pdf_file

Thanks

Jordi
Monday, June 18th, 2018

TextView tv2 = tv_file;
final String testing = tv2.getText().toString();

i mean i cant read testing because utils
and i try public static String downloadPdfUrl3 = testing;
show error
here:
downloadFileName = downloadUrl.replace(Utils.mainUrl, “”);
and here :
new DownloadTask(CatalogDetailActivity.this, DownloadPdf,Utils.downloadPdfUrl3);
mysourcecode:
https://gist.githubusercontent.com/nafsan1/96c2d05d943f8fb6ad94f1fdb0d076a4/raw/cd945a354183eae7b0c755e435064f6f82f55819/androhub.java

Dr. Droid
Tuesday, June 19th, 2018

Hi Jordi,

You need to replace the Utils.downloadPdfUrl3 with testing inside onClickListener where you are executing DownloadTask.

Thanks

surendra
Thursday, June 14th, 2018

public static final String downloadDirectory = “Androhub Downloads”;
i am not able to get the purpose of this line, sir can you please brief it?

Dr. Droid
Friday, June 15th, 2018

Hi Surendra,

This line is basically a folder/directory that is going to create into your storage and all the downloaded files will gonna save into this folder/directory only.

Thanks

surendra
Tuesday, June 19th, 2018

Thank you sir for help! But now i am getting a new error.

W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
06-19 13:43:37.146 3690-3690/? E/Download Task: 12.pdf
06-19 13:43:45.518 3690-3690/? E/Download Task: 18.pptx
06-19 13:43:45.520 1692-1858/? W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
06-19 13:44:02.963 1692-1858/? W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
06-19 13:44:02.963 3690-3690/? E/Download Task: 31.mp4
06-19 13:44:03.594 3690-3716/? W/System.err: java.io.IOException: write failed: ENOSPC (No space left on device)
06-19 13:44:03.594 3690-3716/? W/System.err: at libcore.io.IoBridge.write(IoBridge.java:502)
06-19 13:44:03.594 3690-3716/? W/System.err: at java.io.FileOutputStream.write(FileOutputStream.java:186)
06-19 13:44:03.594 3690-3716/? W/System.err: at com.surendra.retrievefilespart2.DownloadTask$DownloadingTask.doInBackground(DownloadTask.java:141)
06-19 13:44:03.594 3690-3716/? W/System.err: at com.surendra.retrievefilespart2.DownloadTask$DownloadingTask.doInBackground(DownloadTask.java:42)
06-19 13:44:03.594 3690-3716/? W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
06-19 13:44:03.594 3690-3716/? W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
06-19 13:44:03.594 3690-3716/? W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
06-19 13:44:03.594 3690-3716/? W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-19 13:44:03.594 3690-3716/? W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-19 13:44:03.594 3690-3716/? W/System.err: at java.lang.Thread.run(Thread.java:818)
06-19 13:44:03.594 3690-3716/? W/System.err: Caused by: android.system.ErrnoException: write failed: ENOSPC (No space left on device)
06-19 13:44:03.594 3690-3716/? W/System.err: at libcore.io.Posix.writeBytes(Native Method)
06-19 13:44:03.594 3690-3716/? W/System.err: at libcore.io.Posix.write(Posix.java:258)
06-19 13:44:03.594 3690-3716/? W/System.err: at libcore.io.BlockGuardOs.write(BlockGuardOs.java:313)
06-19 13:44:03.594 3690-3716/? W/System.err: at libcore.io.IoBridge.write(IoBridge.java:497)
06-19 13:44:03.594 3690-3716/? W/System.err: … 9 more

Dr. Droid
Tuesday, June 19th, 2018

Hi Surendra,

If you see error logs its clearly written that : Caused by: android.system.ErrnoException: write failed: ENOSPC (No space left on device). That means the downloaded file requires more space then space left in your device. So free-up some space then try.

Thanks

Jordi
Friday, June 22nd, 2018

ok thanks

ada apa\
Friday, June 22nd, 2018

hallo bro
how to change file name after download?
example i have link https://androhub.com/demo/demo.pdf
i want change demo.pdf to android.pdf

Dr. Droid
Sunday, June 24th, 2018

Hi Ada apa,

If you want to change the file name before downloading that you can do it by changing downloadFileName value to anyone required.

But if you want to do after download then you need to make a copy of downloaded file with different name.

Thanks

Naveen Yadav
Tuesday, July 31st, 2018

How I use it browser Application. Because there is no fix URL address for any downloading file, video, images, etc. Please Sir help me.

Ekram hossain
Friday, August 17th, 2018

how to display pdf from server ..?

Dr. Droid
Saturday, August 18th, 2018

Hi Ekram,

First you have to download the PDF from server and after downloading follow the steps given in below link to open/display PDF :
https://stackoverflow.com/questions/9666030/display-pdf-file-inside-my-android-application

Thanks

halil
Wednesday, September 19th, 2018

hi sir, ı try yourcodes but when ı click download button, it says “download failed” on button text (I have no extarnal storage sd card on myphone ) and how to store downloaded files on internal storage(phone storage)?

Dr. Droid
Wednesday, September 19th, 2018

Hi Halil,

May be you are testing in Marshmallow+(API Level 6.0) Devices, in that devices you need to take runtime permissions. Please check the below link for help:
https://www.androhub.com/working-android-marshmallow-6-0-permissions/

Thanks

alex
Wednesday, September 19th, 2018

hello myfriend, I click “download button” on app then nothing happen only write download failed where I did mistake pls help me :/

Dr. Droid
Wednesday, September 19th, 2018

Hi Alex,

May be you are testing in Marshmallow+(API Level 6.0) Devices, in that devices you need to take runtime permissions. Please check the below link for help:
https://www.androhub.com/working-android-marshmallow-6-0-permissions/

Thanks

Golam Mawla
Thursday, October 18th, 2018

Bro i want your email id

Dr. Droid
Thursday, October 18th, 2018

Hi Golam,

You can find the email at top of the blog.

Thanks

Golam Mawla
Thursday, October 18th, 2018

Hi bro, i want to download videos from facebook by java anroid. so how will i do? could you guide me please?

Dr. Droid
Thursday, October 18th, 2018

Hi Golam,

To download any videos or any file from anywhere you should be having the path/link of that file like http://example.com/xyz.mp4.

Thanks

Hussein
Wednesday, October 24th, 2018

Hi bro,

thanks a lot for the great job you did. How can i make it for multi files on the same URL, and make all files downloaded with one button only?

Thanks

prajakta
Friday, November 16th, 2018

hi i want to video download to save in gallery what i can do?

Dr. Droid
Sunday, November 18th, 2018

Hi Prajakta,

To show the downloaded videos or images in gallery you need to tell your gallery to scan new files. You can do it by seeing the code given in below link:

https://stackoverflow.com/questions/35216479/why-the-downloaded-video-from-an-android-app-not-showing-in-the-gallery

Thanks

Akshay
Wednesday, February 6th, 2019

Hlw sir, How can i download a folder from webserver in android

Dr. Droid
Wednesday, February 6th, 2019

Hi Akshay,

If you have gone through post then there is a zip file is also downloading. So the same thing you have to do with your server.
1. Host the zip file on your server.
2. Get a zip file link.
3. Use the code to download the zip file via zip file link(path).

Thanks

Atul
Tuesday, February 12th, 2019

I want my app to download a pdf and view in the same application .. not in other pdf viewer … That is no intent portion… How to do that

Dr. Droid
Tuesday, February 12th, 2019

Hi Atul,

Please check this link.

Thanks

Aqila
Thursday, March 14th, 2019

i want my app to download a pdf file from assets folder. not from the google .
How ?

Dr. Droid
Sunday, March 17th, 2019

Hi Aqila,

Please see this link to know how to save/download assets pdf file to your local storage. See 2nd answer from the link that will help you.

Thanks

Ahlam
Monday, March 25th, 2019

Hi am newbie I want to show the name of the file and size above the download button and then the downloaded files to show in listview in another fragment library that opens onclick

TANMESH SHAH
Monday, April 1st, 2019

button shows download failed and then download again, I think not app is not able to create a request.

Ghasteek
Wednesday, April 17th, 2019

Hello, thank you for nice tutorial. I slightly edited your code, but when Im trying to download 2MB *.apk file, it gets me :
“E/Download Task: Download Error Exception unexpected end of stream”
“E/Download Task: Download Failed”

If i try download 3B text file, it download it correctly….

Some idea to fix that?

Nazmul
Friday, April 26th, 2019

Hello, Thanks for this superb tutorial. I have implemented but got some error. Please help me. I got these errors:

error: cannot find symbol variable outputFile
error: cannot find symbol variable apkStorage

Dr. Droid
Friday, April 26th, 2019

Hi Nazmul,

You can find these variables inside DownloadTask.java class.

Thanks

Littin Moly Mathew
Tuesday, May 14th, 2019

hai sir,thank u for this tutorial. My pdf file is downloaded. It is fine but when click on open downloaded folder the corresponding file shows but not activated and cannot open it.

Dr. Droid
Tuesday, May 14th, 2019

Hi Littin,

To open pdf files your device should have pdf reader to open the pdf files.

Thanks

Syawadhilah Pradipta
Thursday, June 6th, 2019

can I change the url with my folder destination?

Dr. Droid
Wednesday, June 12th, 2019

Hi Syawadhilah,

Yes you can.

Thanks

Dr. Droid
Wednesday, June 12th, 2019

Hi Syawadhilah,

Yes you can.

Thanks

Shahana
Sunday, August 11th, 2019

Hi.. how can i direct the download to phone storage instead of sd card? and how can i open file from phone storage? Your tutorial is awesome.

Dr. Droid
Monday, August 12th, 2019

Hi Shahana,

Check this link for storing the file in Internal/Phone Storage: https://developer.android.com/training/data-storage/files/internal.

Once you store you will be having the path which can be used to open it whenever required.

Thanks

Shahana
Saturday, August 17th, 2019

can you do me a working example..please

Shahana
Sunday, August 18th, 2019

hi…can you tell me how to list the downloaded files within the app in recyclerview

Dr. Droid
Monday, August 26th, 2019

Hi Shahana,

For this, you have to make a call to storage and fetch all the downloaded files and list out in your app.

Check this link: https://stackoverflow.com/questions/8646984/how-to-list-files-in-an-android-directory.

Thanks

Shahana
Monday, September 16th, 2019

hi…can you tell me how to create subfolders like videos,images,documents etc in main app directory…please..thank you

Dr. Droid
Monday, September 16th, 2019

Hi Shahana,

You can do like: apkStorage = new File (Environment.getExternalStorageDirectory() + “/”+ Utils.downloadDirectory+”/”+”Images”); //Like this you can make sub-folders.

I have copied apkStorage from the above article.

Thanks

Shahana
Saturday, September 21st, 2019

hi…sorry for posting now and then and disturbing you.. i need to download videos..audios and images and save into its corresponding folder..but at times ..i get a runtime exception while downloading and also do in background is not working..what shall i do?..please help..thank you

Dr. Droid
Monday, September 23rd, 2019

Hi Shahana,

Can you share your code to my email Id – [email protected].
And also share what runtime exception you are facing?

Thanks

Shahana
Saturday, September 28th, 2019

hi…i wrote this code in fragment…can you tell me how to retain the state of download when switching between fragments

Shahana
Tuesday, September 24th, 2019

i mailed you

Shaneesh
Sunday, October 27th, 2019

if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, “Directory Created.”);
}

I have problem
cannot create directory – apkStorage.mkdir();

plz help me

Dr. Droid
Monday, October 28th, 2019

Hi Shaneesh,

Can you check what is the actual error and also check whether you are trying to create correct directory or not?

Thanks

Hamza
Thursday, December 12th, 2019

I want to add a zip file in an activity in my app and users could save that file to their storage. How can I do that? I want this feature with In-App billing so that people pay and they get access to the extra material which will be in the form of a zip file which can be saved to the phone.

Dr. Droid
Sunday, December 15th, 2019

Hi Hamza,

Please check this link: https://stackoverflow.com/questions/9324103/download-and-extract-zip-file-in-android.

Thanks

HAROLD
Wednesday, January 22nd, 2020

Hello Friend.
How can I get the file to be compared before downloading it?
that is, if the file hosted in the folder is old, then it allows you to download the new one from the web. otherwise it will prevent the download.

Dr. Droid
Thursday, January 23rd, 2020

Hi Harlod,

You can use below code for this:

HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
c.setRequestMethod(“GET”);//Set Request Method to “GET” since we are grtting data
c.connect();//connect the URL Connection

//If Connection response is not OK then show Logs
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, “Server returned HTTP ” + c.getResponseCode()
+ ” ” + c.getResponseMessage());

}

// get download file length
final int lengthOfFile = c.getContentLength();

….
….

outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File

//Create New File if not present
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, “File Created”);
}
else {
Log.e(TAG, “File already created : ” + outputFile.length() + ” – ” + lengthOfFile);
if (outputFile.length() == lengthOfFile) {
Log.e(TAG, “File already downloaded”);
return null;
} else {
//else delete the file and create new
if (outputFile.delete())
if (outputFile.createNewFile())
Log.e(TAG, “New File Created : ” + outputFile);

}
}

this is just a code modification from the existing one.

Thanks

Harol
Monday, January 27th, 2020

Thank you very much for your prompt response …

Unfortunately 🙁

It does not compare the files before downloading them.

What I want is If the file is the same as the host, DO NOT download it. This saves network data.
Imagine the file weighing 30MB, would spend a lot of data every time you press download. This is what I do not want.

Dr. Droid
Tuesday, January 28th, 2020

Hi Harol,

Please check this link: https://stackoverflow.com/questions/16237950/android-check-if-file-exists-without-creating-a-new-one

Hope it helps.

Thanks

Shahana
Thursday, February 6th, 2020

Hi, can you tell me how to show progress of video download within app like in youtube..whatsapp etc.. thanks in advance

Bilal Ahmad
Wednesday, April 22nd, 2020

Hi sir
There is error in DownloadTask class
At mainUrl
Said
Unknown member of Util class
Please sir how to fix it.?

Dr. Droid
Thursday, April 30th, 2020

Hi Bilal,

Can you copy the Utils class from the code and use it in your project.

Thanks

Raj Shrivas
Tuesday, April 28th, 2020

This code is not working on my Android 10 ..can you please tell me the solution …..when i m going to download the file ..it’s says Downloading failed…..but it is working on android 7,8,9….

Dr. Droid
Thursday, April 30th, 2020

Hi Raj,

Can you share your logcat exception over mail?

Thanks

Post comment

Your email address will not be published. Required fields are marked *