Android ImageLoader - load images sequencially in the background
A few days ago I started to learn android… and it’s been a fairly smooth transition from flash. Although I have to say, as flash developers we’re just spoiled. We take for granted all the background stuff flash does for us to make coding that much easier.
One of those things is Loading images. in flash we have the Loader class which makes loading images very easy.
1 2 | var loader:Loader = new Loader(); loader.load(new URLRequest("myimage.jpg")); |
In java/android it takes a few more lines
1 2 3 4 5 6 7 | HttpURLConnection conn = (HttpURLConnection) new URL("myimage.jpg").openConnection(); conn.setDoInput(true); conn.connect(); InputStream inStream = conn.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(inStream); inStream.close(); conn.disconnect(); |
The code above runs in the same thread so you’ll lock up your UI until the image has finish loading. Adding the Threading code adds quite a bit more code. So I decided to create an ImageLoader class to make my life just a little easier. Now I can load an image to an ImageView with one line of code.
1 | ImageLoader.getInstance().load(myImageView, "myimage.jpg", true); |
The last parameter tells the ImageLoader class to cache that the bitmap.
The ImageLoader class loads images sequentially so you don’t slow your mobile device down to a crawl. To cancel Loading simply call clearQueue() and to clear the cache call clearCache()
Here’s the class
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 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | package com.wumedia.net; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.widget.ImageView; public class ImageLoader { static private ImageLoader _instance; static public ImageLoader getInstance() { if (_instance == null) { _instance = new ImageLoader(); } return _instance; } private HashMap<string , Bitmap> _urlToBitmap; private Queue<group> _queue; private DownloadThread _thread; private Bitmap _missing; private boolean _busy; /** * Constructor */ private ImageLoader () { _urlToBitmap = new HashMap<string , Bitmap>(); _queue = new LinkedList<group>(); _busy = false; } public Bitmap get(String url) { return _urlToBitmap.get(url); } public void load(ImageView image, String url) { load(image, url, false); } public void load(ImageView image, String url, boolean cache) { if (_urlToBitmap.get(url) != null) { if(image!=null) { image.setImageBitmap(_urlToBitmap.get(url)); } } else { image.setImageBitmap(null); queue(image, url, cache); } } public void queue(ImageView image, String url, boolean cache) { Iterator</group><group> it = _queue.iterator(); if (image!=null) { while (it.hasNext()) { if (it.next().image.equals(image)) { it.remove(); break; } } } else if (url!=null) { while (it.hasNext()) { if (it.next().url.equals(url)) { it.remove(); break; } } } _queue.add(new Group(image, url, null, cache)); loadNext(); } public void clearQueue() { _queue = new LinkedList</group><group>(); } public void clearCache() { _urlToBitmap = new HashMap<string , Bitmap>(); } public void cancel() { clearQueue(); if ( _thread != null ) { _thread.disconnect(); _thread = null; } } public void setMissingBitmap(Bitmap bitmap) { _missing = bitmap; } private void loadNext() { Iterator<group> it = _queue.iterator(); if (!_busy && it.hasNext() ) { _busy = true; Group group = it.next(); it.remove(); // double check image availability if (_urlToBitmap.get(group.url) != null) { if (group.image!=null) { group.image.setImageBitmap(_urlToBitmap.get(group.url)); } _busy = false; loadNext(); } else { _thread = new DownloadThread(group); _thread.start(); } } } private void onLoad() { if (_thread != null) { Group group = _thread.group; if (group.bitmap != null) { if (group.cache) { _urlToBitmap.put(group.url, group.bitmap); } if (group.image != null) { group.image.setImageBitmap(group.bitmap); } } else if (_missing != null) { if (group.image != null) { group.image.setImageBitmap(_missing); } } } _thread = null; _busy = false; loadNext(); } private class Group { public Group(ImageView image, String url, Bitmap bitmap, boolean cache) { this.image = image; this.url = url; this.bitmap = bitmap; this.cache = cache; } public ImageView image; public String url; public Bitmap bitmap; public boolean cache; } private class DownloadThread extends Thread { final Handler threadHandler = new Handler(); final Runnable threadCallback = new Runnable() { public void run() { onLoad(); } }; private HttpURLConnection _conn; public Group group; public DownloadThread(Group group) { this.group = group; } @Override public void run() { InputStream inStream = null; _conn = null; try { _conn = (HttpURLConnection) new URL(group.url).openConnection(); _conn.setDoInput(true); _conn.connect(); inStream = _conn.getInputStream(); group.bitmap = BitmapFactory.decodeStream(inStream); inStream.close(); _conn.disconnect(); inStream = null; _conn = null; } catch (Exception ex) { // nothing } if (inStream != null) { try { inStream.close(); } catch (Exception ex) {} } disconnect(); inStream = null; _conn = null; threadHandler.post(threadCallback); } public void disconnect() { if (_conn != null) { _conn.disconnect(); } } } } </group></string></group></string></group></string> |
Tags: Android
August 2nd, 2009 at 6:47 am
Thanx for nice piece of code. I think it will be very usefull not even for me
August 11th, 2009 at 5:12 pm
[...] » wu-media.com [...]
September 10th, 2009 at 5:08 am
Thanks for sharing this code!
November 17th, 2009 at 4:06 am
Thanks for sharing this code, its well done! But I have a question about the cache feature. When is the best time to clear the cache? I mean even if my activity is closed by using the back button, it will still be cached right?
December 1st, 2009 at 6:43 am
Nice code… it works well… i used also a LRU cache instead of HashMap for avoid OutOfMemoryException. Nice again.
March 11th, 2010 at 8:06 am
Thanks for sharing this code !… Its working cool!..
March 11th, 2010 at 8:07 am
Its Cool
July 12th, 2010 at 9:43 pm
How I can get ImageLoader into Hashmap which add into ArrayList? SimpleAdapter load ArrayList for ListView.
July 18th, 2010 at 11:30 pm
I made queue a bit simpler, by assuming args are not null, also you can use generics throughout:
public void queue(ImageView image, String url, boolean cache) {
Iterator it = queue.iterator();
if (it.hasNext()) {
Group group = (Group) it.next();
group.image = image;
group.url = url;
it.remove();
}
One problem is that you can run out of memory if you use a lot of images, it’d probably be worth caching them to files instead.
queue.add(new Group(image, url, null, cache));
loadNext();
}