Android AsyncTask - Download Image/Bitmap

android networking

Android AsyncTask - Download Image/Bitmap tutorial.

There are plenty of image downloader libraries.Picasso and Glide are so far my best two.However,the truth is they are third party libraries and have to be added as a dependency in android studio or jar in Eclipse.

Sometimes instead of using third party dependencies you just need to do something using the built in classes.

So in this example we see how to download an image/bitmap in the background thread using asynctask.

AsyncTask is an abstract class that makes threading while updating the UI easier.

What we make?

In this tutorial we will make a simple app to download an image from a server in the background thread when a button is clicked. When the user clicks the download button, the app starts downloading the image while a progressDialog is displayed. We display the progressDialog as it's allows our users track the progress of the download from our app.

Tools Used

In this guide we used to Eclipse to create our simple app while we used BlueStacks Emulator to test the app. Bluestacks Emulator is a free emulator however you are free to test with any emulator like say Genymotion etc.

You can also use an android mobile device like Samsung,HTC,Infinix etc whatever device you are using as long as it runs android. However, you have to provide a URL(Uniform Resource Identifier) that is accessible over the web. In this example I created a simple Wordpress website and downloaded the image from it. But you can also provide an internet URL.

NB/= If you are using the emulator and you are downloaing the image from localhost then use the IP address: instead of or localhost.

1. Our MainActivity Class

Here are the responsibilities for this class:

No. Role
1. It's our launcher activity. This class will derive from
2. Define the URL we will connect to and download the image.
3. Define an inner class that derives from AsyncTask so that we are able to download our image without freezing the UI.
4. Render the an ImageView, a button and a progressbar as our User Interface controls. The button will be clicked to initiate the download. The progressbar will display the progress of the download. The ImageView will render the downloaded image.

Let's go.

First specify the package name:

package com.tutorials.asyncimagedownload;

Then add these imports:

    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ImageView;

Create a class and make it extend

public class MainActivity extends Activity {}

Add the following as instance fields. Please give a url pointing us to the image:

      private String url="";
      ImageView img;
      Button downloadBtn;
      ProgressDialog pd;

If your image is hosted locally then specify the root ip address as I have, that is if you'll be testing in an emulator.

Let's now create an inner class inside our MainActivity. First here are the roles of this inner Downloader class:

No. Role
1. It's responsible for downloading our image in the background thread and rendering it in an imageview.
2. It shows a progress dialog while download in progress and dismisses it when it's over.
private class Downloader {}

Make the class derive from AsyncTask, an abstract class.:

private class Downloader extends AsyncTask<String,Void,Bitmap>{}

AsyncTask is an abstract class, hence you'll have to override at least the doInBackground() method. But for us firs we override the onPreExecute().This method will get called before our doInBackground()

            protected void onPreExecute() {
                // TODO Auto-generated method stub


We'll set up our progressbar and show it here inside the onPreExecute():

                //CREATE PD,SET PROPERTIES
                pd=new ProgressDialog(MainActivity.this);
                pd.setTitle("Image Downloader");

We then override the doInBackground(). This is a must since it's here that our background image downloading will be taking place in a separate thread.

        protected Bitmap doInBackground(String... url) {|

You can see it's returning a Bitmap while taking in a string url. Here's how we download the image. Add the following code inside your doInBackground() method:

          String myurl=url[0];
          Bitmap bm=null;
          InputStream is=null;

            is=new URL(myurl).openStream();


          catch(Exception e)

          return bm;

Then lastly we override the onPostExecute() a method that gets executed when the doInBackground has returned. We set our bitmap to our imageview here and clear the progress dialog.

        protected void onPostExecute(Bitmap result) {
          // TODO Auto-generated method stub

          //SET TO IMG



Now let's go back inside our MainActivity and override it's onCreate() method:

        protected void onCreate(Bundle savedInstanceState) {

Then refernce our widgets: imageview and download button:

            img=(ImageView) findViewById(;
            downloadBtn=(Button) findViewById(;

Then inside our download button's onClickListener execute our AsyncTask, passing in the URL:

          public void onClick(View arg0) {
            // TODO Auto-generated method stub
            new Downloader().execute(url);

2. AndroidMainfest.xml

Then make sure you add the permission to internet in your androidmanifest.xml.

<?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android=""
        android:versionName="1.0" >

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

            android:theme="@style/AppTheme" >
                android:label="@string/app_name" >
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />


3. Our XML Layout

Android apps user interface are written in XML. So we need to write our layout in XML as well. Our root layout tag is going to be a relativelayout. We add a button and an imageview inside it. Just Add ImageView and button to your xml layout.

    <RelativeLayout xmlns:android=""
        tools:context=".MainActivity" >

            android:text="Download" />

            android:src="@drawable/imageloading" />


  And that's it.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:


What do You Think

Previous Post Next Post