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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<resources> <string name="app_name">Android Download Demo</string> <string name="download_Pdf">Download pdf</string> <string name="download_Doc">Download Doc</string> <string name="download_zip">Download Zip</string> <string name="download_video">Download Video</string> <string name="download_mp3">Download MP3</string> <string name="openFolder">Open Downloaded Folder</string> <string name="downloadStarted">Download Started…</string> <string name="downloadCompleted">Download Completed…</string> <string name="downloadFailed">Download Failed…</string> <string name="downloadAgain">Download Again</string> </resources> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#eeeeee" android:orientation="vertical" android:padding="5dp"> <!-- Download Pdf Layout --> <Button android:id="@+id/downloadPdf" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/download_Pdf" /> <!-- Download Doc Layout --> <Button android:id="@+id/downloadDoc" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/download_Doc" /> <!-- Download Zip File Layout --> <Button android:id="@+id/downloadZip" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/download_zip" /> <!-- Download Video File Layout --> <Button android:id="@+id/downloadVideo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/download_video" /> <!-- Download MP3 File Layout --> <Button android:id="@+id/downloadMp3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/download_mp3" /> <!-- Open Downloaded Folder --> <Button android:id="@+id/openDownloadedFolder" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="@string/openFolder" /> </LinearLayout> |
4. Create a Utils.java class and write all download urls here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.androiddownloaddemo; /** * Created by SONU on 29/10/15. */ public class Utils { //String Values to be Used in App public static final String downloadDirectory = "Androhub Downloads"; public static final String mainUrl = "https://androhub.com/demo/"; public static final String downloadPdfUrl = "https://androhub.com/demo/demo.pdf"; public static final String downloadDocUrl = "https://androhub.com/demo/demo.doc"; public static final String downloadZipUrl = "https://androhub.com/demo/demo.zip"; public static final String downloadVideoUrl = "https://androhub.com/demo/demo.mp4"; public static final String downloadMp3Url = "https://androhub.com/demo/demo.mp3"; } |
5. Create a CheckForSDCard.java class for checking if SDCard is present or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.androiddownloaddemo; import android.os.Environment; public class CheckForSDCard { //Check If SD Card is present or not method public boolean isSDCardPresent() { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { return true; } return false; } } |
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:
1 |
URL url = new URL(downloadUrl); |
2. Opening Url Connection for data downloading:
1 |
HttpURLConnection c = (HttpURLConnection) url.openConnection(); |
3. Setting request method to server:
1 |
c.setRequestMethod("GET"); |
4. Connect the open connection:
1 |
c.connect(); |
5. Create a directory in SD Card if not present:
1 2 3 |
File apkStorage = new File( Environment.getExternalStorageDirectory() + "/" + Utils.downloadDirectory); |
1 2 3 4 |
if (!apkStorage.exists()) { apkStorage.mkdir(); Log.e(TAG, "Directory Created."); } |
6. Create an Output file i.e. download file inside above created directory:
1 |
String downloadFileName = downloadUrl.replace(Utils.mainUrl, "");//Create file name by picking download file name from URL |
1 |
File outputFile = new File(apkStorage, downloadFileName); |
1 2 3 4 |
if (!outputFile.exists()) { outputFile.createNewFile(); Log.e(TAG, "File Created"); } |
Note: Give extension to your outputFile like .pdf, .mp3, .mp4 etc.
7. Download File and write it over the outputFile created:
1 2 3 4 5 6 7 8 9 |
FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location InputStream is = c.getInputStream();//Get InputStream for connection byte[] buffer = new byte[1024];//Set buffer type int len1 = 0;//init length while ((len1 = is.read(buffer)) != -1) { fos.write(buffer, 0, len1);//Write new file } |
8. Close all connection after downloading:
1 2 |
fos.close(); is.close(); |
Full Code of DownloadTask.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
package com.androiddownloaddemo; import android.content.Context; import android.os.AsyncTask; import android.os.Environment; import android.os.Handler; import android.util.Log; import android.widget.Button; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Created by SONU on 29/10/15. */ public class DownloadTask { private static final String TAG = "Download Task"; private Context context; private Button buttonText; private String downloadUrl = "", downloadFileName = ""; public DownloadTask(Context context, Button buttonText, String downloadUrl) { this.context = context; this.buttonText = buttonText; this.downloadUrl = downloadUrl; downloadFileName = downloadUrl.replace(Utils.mainUrl, "");//Create file name by picking download file name from URL Log.e(TAG, downloadFileName); //Start Downloading Task new DownloadingTask().execute(); } private class DownloadingTask extends AsyncTask<Void, Void, Void> { File apkStorage = null; File outputFile = null; @Override protected void onPreExecute() { super.onPreExecute(); buttonText.setEnabled(false); buttonText.setText(R.string.downloadStarted);//Set Button Text when download started } @Override protected void onPostExecute(Void result) { try { if (outputFile != null) { buttonText.setEnabled(true); buttonText.setText(R.string.downloadCompleted);//If Download completed then change button text } else { buttonText.setText(R.string.downloadFailed);//If download failed change button text new Handler().postDelayed(new Runnable() { @Override public void run() { buttonText.setEnabled(true); buttonText.setText(R.string.downloadAgain);//Change button text again after 3sec } }, 3000); Log.e(TAG, "Download Failed"); } } catch (Exception e) { e.printStackTrace(); //Change button text if exception occurs buttonText.setText(R.string.downloadFailed); new Handler().postDelayed(new Runnable() { @Override public void run() { buttonText.setEnabled(true); buttonText.setText(R.string.downloadAgain); } }, 3000); Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage()); } super.onPostExecute(result); } @Override protected Void doInBackground(Void... arg0) { try { URL url = new URL(downloadUrl);//Create Download URl 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 File if SD card is present if (new CheckForSDCard().isSDCardPresent()) { apkStorage = new File( Environment.getExternalStorageDirectory() + "/" + Utils.downloadDirectory); } else Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show(); //If File is not present create directory if (!apkStorage.exists()) { apkStorage.mkdir(); Log.e(TAG, "Directory Created."); } 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"); } FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location InputStream is = c.getInputStream();//Get InputStream for connection byte[] buffer = new byte[1024];//Set buffer type int len1 = 0;//init length while ((len1 = is.read(buffer)) != -1) { fos.write(buffer, 0, len1);//Write new file } //Close all connection after doing task fos.close(); is.close(); } catch (Exception e) { //Read exception if something went wrong e.printStackTrace(); outputFile = null; Log.e(TAG, "Download Error Exception " + e.getMessage()); } return null; } } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
//Open downloaded folder private void openDownloadedFolder() { //First check if SD Card is present or not if (new CheckForSDCard().isSDCardPresent()) { //Get Download Directory File File apkStorage = new File( Environment.getExternalStorageDirectory() + "/" + Utils.downloadDirectory); //If file is not present then display Toast if (!apkStorage.exists()) Toast.makeText(MainActivity.this, "Right now there is no directory. Please download some file first.", Toast.LENGTH_SHORT).show(); else { //If directory is present Open Folder /** Note: Directory will open only if there is a app to open directory like File Manager, etc. **/ Intent intent = new Intent(Intent.ACTION_GET_CONTENT); Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/" + Utils.downloadDirectory); intent.setDataAndType(uri, "file/*"); startActivity(Intent.createChooser(intent, "Open Download Folder")); } } else Toast.makeText(MainActivity.this, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show(); } |
Full MainActivity.java Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
package com.androiddownloaddemo; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.io.File; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static Button downloadPdf, downloadDoc, downloadZip, downloadVideo, downloadMp3, openDownloadedFolder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); setListeners(); } //Initialize al Views private void initViews() { downloadPdf = (Button) findViewById(R.id.downloadPdf); downloadDoc = (Button) findViewById(R.id.downloadDoc); downloadZip = (Button) findViewById(R.id.downloadZip); downloadVideo = (Button) findViewById(R.id.downloadVideo); downloadMp3 = (Button) findViewById(R.id.downloadMp3); openDownloadedFolder = (Button) findViewById(R.id.openDownloadedFolder); } //Set Listeners to Buttons private void setListeners() { downloadPdf.setOnClickListener(this); downloadDoc.setOnClickListener(this); downloadZip.setOnClickListener(this); downloadVideo.setOnClickListener(this); downloadMp3.setOnClickListener(this); openDownloadedFolder.setOnClickListener(this); } @Override public void onClick(View view) { //Before starting any download check internet connection availability switch (view.getId()) { case R.id.downloadPdf: if (isConnectingToInternet()) new DownloadTask(MainActivity.this, downloadPdf, Utils.downloadPdfUrl); else Toast.makeText(MainActivity.this, "Oops!! There is no internet connection. Please enable internet connection and try again.", Toast.LENGTH_SHORT).show(); break; case R.id.downloadDoc: if (isConnectingToInternet()) new DownloadTask(MainActivity.this, downloadDoc, Utils.downloadDocUrl); else Toast.makeText(MainActivity.this, "Oops!! There is no internet connection. Please enable internet connection and try again.", Toast.LENGTH_SHORT).show(); break; case R.id.downloadZip: if (isConnectingToInternet()) new DownloadTask(MainActivity.this, downloadZip, Utils.downloadZipUrl); else Toast.makeText(MainActivity.this, "Oops!! There is no internet connection. Please enable internet connection and try again.", Toast.LENGTH_SHORT).show(); break; case R.id.downloadVideo: if (isConnectingToInternet()) new DownloadTask(MainActivity.this, downloadVideo, Utils.downloadVideoUrl); else Toast.makeText(MainActivity.this, "Oops!! There is no internet connection. Please enable internet connection and try again.", Toast.LENGTH_SHORT).show(); break; case R.id.downloadMp3: if (isConnectingToInternet()) new DownloadTask(MainActivity.this, downloadMp3, Utils.downloadMp3Url); else Toast.makeText(MainActivity.this, "Oops!! There is no internet connection. Please enable internet connection and try again.", Toast.LENGTH_SHORT).show(); break; case R.id.openDownloadedFolder: openDownloadedFolder(); break; } } //Open downloaded folder private void openDownloadedFolder() { //First check if SD Card is present or not if (new CheckForSDCard().isSDCardPresent()) { //Get Download Directory File File apkStorage = new File( Environment.getExternalStorageDirectory() + "/" + Utils.downloadDirectory); //If file is not present then display Toast if (!apkStorage.exists()) Toast.makeText(MainActivity.this, "Right now there is no directory. Please download some file first.", Toast.LENGTH_SHORT).show(); else { //If directory is present Open Folder /** Note: Directory will open only if there is a app to open directory like File Manager, etc. **/ Intent intent = new Intent(Intent.ACTION_GET_CONTENT); Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/" + Utils.downloadDirectory); intent.setDataAndType(uri, "file/*"); startActivity(Intent.createChooser(intent, "Open Download Folder")); } } else Toast.makeText(MainActivity.this, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show(); } //Check if internet is present or not private boolean isConnectingToInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager .getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) return true; else return false; } } |
8. Finally come to AndroidManifest.xml file and add below several permissions to Manifest file.
1 2 3 4 5 6 7 8 9 |
<!-- Permission required for Downloading Files --> <uses-permission android:name="android.permission.INTERNET" /> <!-- Permission required for Checking Internet Connection --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- Permission required for Reading Writing SD Card/Memory --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> |
9. Finally, all done you can use above steps for downloading any kind of files.
Thanks.
Subscribe to us and get the latest news.
95 Comments
Arjun
Wednesday, May 24th, 2017Not working. Shows IO Execption.
Dr. Droid
Wednesday, May 24th, 2017Hi 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, 2017It 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, 2017Hi 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, 2017It is possible to show the percentage of download for each file?
Dr. Droid
Friday, July 21st, 2017Hi Juan,
Please follow the below link to show percentage while downloading each file : https://www.androhub.com/android_progressbar/
Thanks
moh99
Friday, July 21st, 2017Hi, 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, 2017Hi 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, 2017Thanks. 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, 2017Hi 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, 2017Error in code. You are trying to update UI from doInBackground. Try to use RunonUiThread to show Toast.
Jagdish
Tuesday, October 10th, 2017Dr 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, 2017Thanks 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, 2018Thanks 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, 2018good job sir.
all code work perfectly.
but is it possible to download files from google drive
thanks in andvance
Dr. Droid
Monday, May 7th, 2018Hi 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, 2018working 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, 2018Hi Sagar,
Please change the main url also : public static final String mainUrl = “https://androhub.com/demo/”;
Thanks
mind
Monday, May 28th, 2018how toafter download file show listview file?
example file pdf
thanks
babang
Wednesday, May 30th, 2018how to download all file in one folder?
Dr. Droid
Wednesday, May 30th, 2018Hi Babang,
The above given code is already downloading all files in single directory only.
Thanks
PleaseHelpMe
Friday, June 1st, 2018hey 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, 2018Hi PleaseHelpMe,
You need to implement DownloadManager.
Please check this link : https://developer.android.com/reference/android/app/DownloadManager.
Thanks
PleaseHelpMe
Friday, June 1st, 2018ok thanks
Jordi
Monday, June 11th, 2018Hello 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, 2018Hi 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, 2018hello 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, 2018Hi 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, 2018TextView 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, 2018Hi Jordi,
You need to replace the Utils.downloadPdfUrl3 with testing inside onClickListener where you are executing DownloadTask.
Thanks
surendra
Thursday, June 14th, 2018public 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, 2018Hi 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, 2018Thank 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, 2018Hi 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, 2018ok thanks
ada apa\
Friday, June 22nd, 2018hallo 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, 2018Hi 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, 2018How 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, 2018how to display pdf from server ..?
Dr. Droid
Saturday, August 18th, 2018Hi 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, 2018hi 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, 2018Hi 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, 2018hello 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, 2018Hi 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, 2018Bro i want your email id
Dr. Droid
Thursday, October 18th, 2018Hi Golam,
You can find the email at top of the blog.
Thanks
Golam Mawla
Thursday, October 18th, 2018Hi 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, 2018Hi 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, 2018Hi 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, 2018hi i want to video download to save in gallery what i can do?
Dr. Droid
Sunday, November 18th, 2018Hi 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, 2019Hlw sir, How can i download a folder from webserver in android
Dr. Droid
Wednesday, February 6th, 2019Hi 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, 2019I 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, 2019Hi Atul,
Please check this link.
Thanks
Aqila
Thursday, March 14th, 2019i want my app to download a pdf file from assets folder. not from the google .
How ?
Dr. Droid
Sunday, March 17th, 2019Hi 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, 2019Hi 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, 2019button shows download failed and then download again, I think not app is not able to create a request.
Ghasteek
Wednesday, April 17th, 2019Hello, 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, 2019Hello, 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, 2019Hi Nazmul,
You can find these variables inside DownloadTask.java class.
Thanks
Littin Moly Mathew
Tuesday, May 14th, 2019hai 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, 2019Hi Littin,
To open pdf files your device should have pdf reader to open the pdf files.
Thanks
Syawadhilah Pradipta
Thursday, June 6th, 2019can I change the url with my folder destination?
Dr. Droid
Wednesday, June 12th, 2019Hi Syawadhilah,
Yes you can.
Thanks
Dr. Droid
Wednesday, June 12th, 2019Hi Syawadhilah,
Yes you can.
Thanks
Shahana
Sunday, August 11th, 2019Hi.. 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, 2019Hi 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, 2019can you do me a working example..please
Shahana
Sunday, August 18th, 2019hi…can you tell me how to list the downloaded files within the app in recyclerview
Dr. Droid
Monday, August 26th, 2019Hi 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, 2019hi…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, 2019Hi 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, 2019hi…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, 2019Hi 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, 2019hi…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, 2019i mailed you
Shaneesh
Sunday, October 27th, 2019if (!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, 2019Hi 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, 2019I 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, 2019Hi Hamza,
Please check this link: https://stackoverflow.com/questions/9324103/download-and-extract-zip-file-in-android.
Thanks
HAROLD
Wednesday, January 22nd, 2020Hello 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, 2020Hi 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, 2020Thank 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, 2020Hi 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, 2020Hi, can you tell me how to show progress of video download within app like in youtube..whatsapp etc.. thanks in advance
Dr. Droid
Thursday, February 6th, 2020Hi Shahana,
Please check this link: https://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog
Thanks
Bilal Ahmad
Wednesday, April 22nd, 2020Hi 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, 2020Hi Bilal,
Can you copy the Utils class from the code and use it in your project.
Thanks
Raj Shrivas
Tuesday, April 28th, 2020This 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, 2020Hi Raj,
Can you share your logcat exception over mail?
Thanks