Translate this page

Android Download a File from Internet URL in Java

How to Download a File from URL Link in Android Java Tutorial

This tutorial will guide you to learn how to download a file from web in android java, we will first get a link to an image for downloading it, add required permissions and then pass the download link to the download manager for downloading, we will also set a path for saving the file to a location in the android device. If you can’t do it, you can contact me, i will fix or add it for you (see below for contact details)

First, Create a new android project in Android Studio or use an existing project.

Add these permissions in AndroidManifest.xml

 
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

 

Next, we need an image to test our download code, let’s try this cat’s image that is hosted in this website.

This is the direct link of the cat’s image

https://www.zidsworld.com/wp-content/uploads/2018/06/cat_1530281469.jpg

 

 

Open the MainActivity.java, Then add this code, this code should be placed below OnCreate method.

try {
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES), "myfolder");


if (!imageStorageDir.exists()) {
//noinspection ResultOfMethodCallIgnored
imageStorageDir.mkdirs();
}

// default image extension
String imgExtension = ".jpg";

if (image_uri.toString().contains(".gif"))
imgExtension = ".gif";
else if (image_uri.toString().contains(".png"))
imgExtension = ".png";
else if (image_uri.toString().contains(".3gp"))
imgExtension = ".3gp";

String date = DateFormat.getDateTimeInstance().format(new Date());
String file = getString(R.string.app_name) + "-image-" + date.replace(" ", "").replace(":", "").replace(".", "") + imgExtension;




DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
              Uri downloadUri = Uri.parse("https://www.zidsworld.com/wp-content/uploads/2018/06/cat_1530281469.jpg");
              DownloadManager.Request request = new DownloadManager.Request(downloadUri);

              request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                      .setDestinationInExternalPublicDir(DIRECTORY_PICTURES + File.separator, file)
                      .setTitle(file).setDescription(getString(R.string.save_img))
                      .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

              dm.enqueue(request);

              Toast.makeText(getApplicationContext(), getString(R.string.downloading_img), Toast.LENGTH_LONG).show();


          } catch (IllegalStateException ex) {
              Toast.makeText(getApplicationContext(),"Storage Error", Toast.LENGTH_LONG).show();
              ex.printStackTrace();
          } catch (Exception ex) {
              // just in case, it should never be called anyway
              Toast.makeText(getApplicationContext(),"Unable to save image", Toast.LENGTH_LONG).show();
              ex.printStackTrace();


          }}

 

 

So this is the code for downloading image from a Web link URL to your android device’s pictures directory, the code will be executed as soon as you start the app or the MainActivity.

Conclusion

  • This code will not cause exceptions because exceptions are caught, so your app will not crash when executing this code
  • If your android device runs on marshmallow, you will need request permission before executing this code.
  • This code is just for test, you can assign this code to a button or to your desired activity.
  • You can try other direct download links to test this code

Update: If you are new to android development, or just want fix this error, i can fix it for you for a small fee of US $5. Just send me your project or that java/kotlin file (The Activity where you wish to add this code) through email or google drive,  i can also do it online through TeamViewerAnyDesk etc. I will fix your project or file and send it back to you. You can pay me through Paypal, PayTM, GooglePay, PhonePe, UPI etc. For more details, contact me below

Contact Now


Meet Advanced Plus

I highly recommend you use the new and advanced Android Webview Advanced Plus Source Code we developed to easily convert any website to android app. No coding required, just set your website link, app color, icon etc and the app will be ready!, and it supports upload, download (blob pdf download also supported), loading progress bars, notification, night mode etc. To learn more about the Android Advanced Webview Source Code and to download it, head over to this page Download Android Webview Source Code

Related Posts

Get Your Own Android Mobile App for Your Website Today

Are you looking to expand your online presence and reach more customers? In today’s digital age, having a mobile app is an essential tool to connect with…

Why making an app for your website can help your business to grow

In today’s digital age, it’s more important than ever to have a strong online presence. Whether you’re running a business, a blog, or a personal website, having…

person using macbook pro on person s lap

Fix android.content.Intent.migrateExtraStreamToClipData(android.content.Context)’ on a null object reference

Here is how to Fix Android Studio Error Attempt to invoke virtual method ‘boolean android.content.Intent.migrateExtraStreamToClipData(android.content.Context)’ on a null object reference This error is caused by a number…

Android Spinner onItemSelected Listener Example

Spinner is an android UI element; it provides a drop-down List where you can choose an item from the list. You will need a listener to catch…

person in gray shirt holding a small paper with texts

Get Current Month Name in Java Android

The code below can be used to get the name of current month, for example, January, February, March etc. Just call this method and it will return…

The future of android developers is not good

Are you an android developer or looking to be an android developer? You should read this Myself is zid, I’m an android developer and been in this…

This Post Has One Comment

Leave a Reply

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