The Complete Guide to Downloading Images from URL on Android: Granting Write External Storage Permission and Reading from Storage

Posted by

How to Download Image from URL in Android

How to Download Image from URL in Android

Downloading an image from a URL in Android can be achieved by using the following steps:

  1. Make sure to add the necessary permissions in the AndroidManifest.xml file to access external storage. Use the following code:

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

  3. Next, you will need to request permissions at runtime. Use the following code to do so:

  4. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE);

  5. After acquiring the necessary permissions, you can proceed with downloading the image from the URL.
  6. Use the following code snippet to download the image:

  7. AsyncTask.execute(new Runnable() {
    @Override
    public void run() {
    try {
    URL url = new URL("https://www.example.com/image.jpg");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.connect();
    InputStream input = connection.getInputStream();
    File file = new File(Environment.getExternalStorageDirectory(), "image.jpg");
    OutputStream output = new FileOutputStream(file);
    byte[] data = new byte[1024];
    int count;
    while ((count = input.read(data)) != -1) {
    output.write(data, 0, count);
    }
    output.flush();
    output.close();
    input.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    });

  8. Once the image is downloaded, you can read it from the storage using the following code:

  9. Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/image.jpg");
    imageView.setImageBitmap(bitmap);

By following these steps, you can easily download an image from a URL in Android, write external storage permissions, and read from the storage.

0 0 votes
Article Rating
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@ganeshvinoth2601
5 months ago

Hi sir, can you please share me this project source zip file which will help me to learn 🙏🏼

@Shoaib.014
5 months ago

How to Download Audio from URL android 13 please make video

@landscapemaker2650
5 months ago

hello sir,Please give me this project code zip file.

@TheSixled
5 months ago

Hello, I have my app folder hosted in Documents and it won't let me use the files, it gives me a permission error, I can only create files and folders, what is the permission it asks for?