Example AsyncTask Android for downloading Images


I see a lot of people asking about how to create AsyncTask() for downloading bitmap images in Android. So, here are some simple example of AsyncTask for download images :

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
class DownloadImageTask extends AsyncTask<Object, Void, Object[]> {
    @Override
    protected Object[] doInBackground(Object… params) {
        Log.v("App", "Progress");
        Bitmap picture = getImageBitmap((String) params[2]);
        Object[] result = new Object[3];
        result[0] = params[0];
        result[1] = params[1];
        result[2] = picture;
       
        return result;
    }
   
    @Override
    protected void onPostExecute(Object[] result) {
        Log.v("Download", "Done");
//          listAdapter.setitem_image((Integer)result[0], (Bitmap) result[2]);
//          listAdapter.setitem_loading((Integer)result[0], false);
    }
}

private Bitmap getImageBitmap(String url) {
    Bitmap bm = null;
    try {
        URL aURL = new URL(url);
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        bm = BitmapFactory.decodeStream(bis);
        bis.close();
        is.close();
   } catch (IOException e) {
       Log.e(url, "Error getting bitmap", e);
   }
   return bm;
}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.