## Saturday, August 27, 2011

### Lazy loading of images in Listview

A common scenario is adding images to a Listview. For example, if you´re making a cocktail recipe app, you´d want a picture next to the cocktail name. Sometimes the images should be retrieved from the internet and then be displayed. Unfortunately, this is difficult to do right. If you´ve tried it, you´ve probably noticed performance hits, or some strange glitches. In this tutorial, I´ll show you how to download images and display them. We´ll also discuss some pitfalls, like recycling and concurrency.

Setting up the listview
I assume you already know how to define a row layout for a Listview and know about adapters.

Below is an example of an adapter for an RSS reader. The text data is retrieved from an Article class, which contains the title of the Article, the author and the publication date. To make the tutorial more clear, I have an explicit list of URLs that will be used for the images of each entry.

public class ListAdapter extends ArrayAdapter<Article> {
private List<Article> articles;
private Context context;
private final LayoutInflater inflator;

private static final String[] URLS = {
"http://lh5.ggpht.com/_Z6tbBnE-swM/TB0CryLkiLI/AAAAAAAAVSo/n6B78hsDUz4/s144-c/_DSC3454.jpg",
"http://lh3.ggpht.com/_GEnSvSHk4iE/TDSfmyCfn0I/AAAAAAAAF8Y/cqmhEoxbwys/s144-c/_MG_3675.jpg",
"http://lh6.ggpht.com/_Nsxc889y6hY/TBp7jfx-cgI/AAAAAAAAHAg/Rr7jX44r2Gc/s144-c/IMGP9775a.jpg",
"http://lh3.ggpht.com/_lLj6go_T1CQ/TCD8PW09KBI/AAAAAAAAQdc/AqmOJ7eg5ig/s144-c/Juvenile%20Gannet%20despute.jpg",
"http://lh6.ggpht.com/_ZN5zQnkI67I/TCFFZaJHDnI/AAAAAAAABVk/YoUbDQHJRdo/s144-c/P9250508.JPG",
"http://lh4.ggpht.com/_XjNwVI0kmW8/TCOwNtzGheI/AAAAAAAAC84/SxFJhG7Scgo/s144-c/0014.jpg",
"http://lh6.ggpht.com/_lnDTHoDrJ_Y/TBvKsJ9qHtI/AAAAAAAAG6g/Zll2zGvrm9c/s144-c/000007.JPG",
"http://lh6.ggpht.com/_qvCl2efjxy0/TCIVI-TkuGI/AAAAAAAAOUY/vbk9MURsv48/s144-c/DSC_0844.JPG",
"http://lh4.ggpht.com/_4f1e_yo-zMQ/TCe5h9yN-TI/AAAAAAAAXqs/8X2fIjtKjmw/s144-c/IMG_1786.JPG",
"http://lh5.ggpht.com/_hepKlJWopDg/TB-_WXikaYI/AAAAAAAAElI/715k4NvBM4w/s144-c/IMG_0075.JPG",
"http://lh6.ggpht.com/_OfRSx6nn68g/TCzsQic_z3I/AAAAAAABOOI/5G4Kwzb2qhk/s144-c/EASTER%20ISLAND_Hanga%20Roa_31.5.08_46.JPG",
"http://lh6.ggpht.com/_ZGv_0FWPbTE/TB-_GLhqYBI/AAAAAAABVxs/cVEvQzt0ke4/s144-c/IMG_1288_hf.jpg",
"http://lh6.ggpht.com/_a29lGRJwo0E/TBqOK_tUKmI/AAAAAAAAVbw/UloKpjsKP3c/s144-c/31012332.jpg",
"http://lh3.ggpht.com/_55Lla4_ARA4/TB6xbyxxJ9I/AAAAAAABTWo/GKe24SwECns/s144-c/Bluebird%20049.JPG",
"http://lh3.ggpht.com/_iVnqmIBYi4Y/TCaOH6rRl1I/AAAAAAAA1qg/qeMerYQ6DYo/s144-c/Kwiat_100626_0016.jpg",
"http://lh6.ggpht.com/_QFsB_q7HFlo/TCItd_2oBkI/AAAAAAAAFsk/4lgJWweJ5N8/s144-c/3705226938_d6d66d6068_o.jpg",
"http://lh5.ggpht.com/_JTI0xxNrKFA/TBsKQ9uOGNI/AAAAAAAChQg/z8Exh32VVTA/s144-c/CRW_0015-composite.jpg",
"http://lh4.ggpht.com/_L7i4Tra_XRY/TBtxjScXLqI/AAAAAAAAE5o/ue15HuP8eWw/s144-c/opera%20house%20II.jpg",
"http://lh3.ggpht.com/_rfAz5DWHZYs/S9cstBTv1iI/AAAAAAAAeYA/EyZPUeLMQ98/s144-c/DSC_6425.jpg",
"http://lh6.ggpht.com/_iGI-XCxGLew/S-iYQWBEG-I/AAAAAAAACB8/JuFti4elptE/s144-c/norvig-polar-bear.jpg",
"http://lh3.ggpht.com/_M3slUPpIgmk/SlbnavqG1cI/AAAAAAAACvo/z6-CnXGma7E/s144-c/mf_003.jpg",
"http://lh5.ggpht.com/_6_dLVKawGJA/SMwq86HlAqI/AAAAAAAAG5U/q1gDNkmE5hI/s144-c/mobius-glow.jpg",
"http://lh3.ggpht.com/_QFsB_q7HFlo/TCItc19Jw3I/AAAAAAAAFs4/nPfiz5VGENk/s144-c/4551649039_852be0a952_o.jpg",
"http://lh6.ggpht.com/_TQY-Nm7P7Jc/TBpjA0ks2MI/AAAAAAAABcI/J6ViH98_poM/s144-c/IMG_6517.jpg",
"http://lh3.ggpht.com/_rfAz5DWHZYs/S9cLAeKuueI/AAAAAAAAeYU/E19G8DOlJRo/s144-c/DSC_4397_8_9_tonemapped2.jpg",
"http://lh4.ggpht.com/_TQY-Nm7P7Jc/TBpi6rKfFII/AAAAAAAABbg/79FOc0Dbq0c/s144-c/david_lee_sakura.jpg",
"http://lh3.ggpht.com/_TQY-Nm7P7Jc/TBpi8EJ4eDI/AAAAAAAABb0/AZ8Cw1GCaIs/s144-c/Hokkaido%20Swans.jpg",
"http://lh3.ggpht.com/_1aZMSFkxSJI/TCIjB6od89I/AAAAAAAACHM/CLWrkH0ziII/s144-c/079.jpg",
"http://lh3.ggpht.com/_0YSlK3HfZDQ/TCExCG1Zc3I/AAAAAAAAX1w/9oCH47V6uIQ/s144-c/3138923889_a7fa89cf94_o.jpg",
"http://lh6.ggpht.com/_K29ox9DWiaM/TAXe4Fi0xTI/AAAAAAAAVIY/zZA2Qqt2HG0/s144-c/IMG_7100.JPG",
"http://lh6.ggpht.com/_0YSlK3HfZDQ/TCEx16nJqpI/AAAAAAAAX1c/R5Vkzb8l7yo/s144-c/4235400281_34d87a1e0a_o.jpg",
"http://lh4.ggpht.com/_8zSk3OGcpP4/TBsOVXXnkTI/AAAAAAAAAEo/0AwEmuqvboo/s144-c/yosemite_forrest.jpg",
"http://lh4.ggpht.com/_6_dLVKawGJA/SLZToqXXVrI/AAAAAAAAG5k/7fPSz_ldN9w/s144-c/coastal-1.jpg",
"http://lh4.ggpht.com/_WW8gsdKXVXI/TBpVr9i6BxI/AAAAAAABhNg/KC8aAJ0wVyk/s144-c/IMG_6233_1_2-2.jpg",
"http://lh3.ggpht.com/_syQa1hJRWGY/TBwkCHcq6aI/AAAAAAABBEg/R5KU1WWq59E/s144-c/Antelope.JPG",
"http://lh4.ggpht.com/_DJGvVWd7IEc/TBpRsGjdAyI/AAAAAAAAFNw/rdvyRDgUD8A/s144-c/Free.jpg",
"http://lh6.ggpht.com/_iO97DXC99NY/TBwq3_kmp9I/AAAAAAABcz0/apq1ffo_MZo/s144-c/IMG_0682_cp.jpg",
"http://lh4.ggpht.com/_7V85eCJY_fg/TBpXudG4_PI/AAAAAAAAPEE/8cHJ7G84TkM/s144-c/20100530_120257_0273-Edit-2.jpg" };

private static class ViewHolder {
public ImageView iconView;
public TextView nameTextView;
public TextView bottomText;
}

public ListAdapter(Context context, int textViewResourceId,
List<Article> articles) {
super(context, textViewResourceId, articles);
this.articles = articles;
this.context = context;
inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

BitmapManager.INSTANCE.setPlaceholder(BitmapFactory.decodeResource(
context.getResources(), R.drawable.icon));
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;

if (convertView == null) {
convertView = inflator.inflate(R.layout.article_row, null);

TextView nameTextView = (TextView) convertView
.findViewById(R.id.title);
TextView bottomText = (TextView) convertView
.findViewById(R.id.bottomtext);
ImageView iconView = (ImageView) convertView
.findViewById(R.id.article_icon);
holder = new ViewHolder();
holder.nameTextView = nameTextView;
holder.bottomText = bottomText;
holder.iconView = iconView;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}

Article article = articles.get(position);
holder.nameTextView.setText(article.getTitle());
holder.bottomText.setText(article.getAuthor() + " | "
+ article.getPubDate());

holder.iconView.setTag(URLS[position]);
32);

return convertView;
}
}



As you can see, I am recycling the view, because I only inflate from XML when convertView == null. I also store references to all the children views in a tag. Recycling and tagging greatly improves performance, as can be seen in this Google Conference video.

A naive way to download a bitmap is to just make a http connection in the getView and set the bitmap using iconView.setImageBitmap(). This would cause severe lag, because the UI thread would have to wait until the image is downloaded. What we want is to download in a separate thread. We also want some kind of cache to store downloaded bitmaps.

All this can be done in a singleton BitmapManager. Here is the download function:

private Bitmap downloadBitmap(String url, int width, int height) {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
url).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
cache.put(url, new SoftReference<Bitmap>(bitmap));
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}

I don't know if this is the optimal way to download a file, so if you know a better way, please leave a message. As you can see, the bitmap is stored in cache, which is defined as Map<String, SoftReference<Bitmap>> cache;. We are using a SoftReference, because we want the bitmap to be garbage collected if the VM is low on memory.

The recycle trap
As I've mentioned before, the row view can be recycled. This means that, if you're scrolling, the view of a row that slides off the screen, can be used as the view of a row that comes into the screen. For example, row 1 disappears and row 3 appears during scrolling. When row 1 was on the screen, the download of the image started. Now imagine that the downloaded of the image of row 1 takes a very long time. When row 3 appears, the image of row 3 is put into the queue. It may happen that this download finishes before the one of row 1, which means that the picture of row 3 will be the one of row 1.

Row 1 visible: start download of image 1
Scrolling
Row 3 visible (recycled view of row 1): start download of image 3
Download of image 3 done: row 3 image set to image 3
Download of image 1 done: row 3 image set to image 1


In order to avoid these recycling issues, we have to store the URL that is lastly associated with the ImageView. If a download is completed, but is not associated with the view anymore (image 1, in the example above), the download is ignored. This is the association map: Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());.

Retrieving the bitmap
 public void loadBitmap(final String url, final ImageView imageView,
final int width, final int height) {
imageViews.put(imageView, url);
Bitmap bitmap = getBitmapFromCache(url);

// check in UI thread, so no concurrency issues
if (bitmap != null) {
Log.d(null, "Item loaded from cache: " + url);
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageBitmap(placeholder);
queueJob(url, imageView, width, height);
}
}

The first thing we do when we load the bitmap, is associating the URL with the ImageView. Then we see if the bitmap is in the cache. If so, we load it from cache, or else we queue the download.
It should be noted that the loadBitmap function is called in the UI thread, which means that we don't have to check if the imageView is recycled and we can call functions like setImageBitmap directly.

public void queueJob(final String url, final ImageView imageView,
final int width, final int height) {
/* Create handler in UI thread. */
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
String tag = imageViews.get(imageView);
if (tag != null && tag.equals(url)) {
if (msg.obj != null) {
imageView.setImageBitmap((Bitmap) msg.obj);
} else {
imageView.setImageBitmap(placeholder);
Log.d(null, "fail " + url);
}
}
}
};

pool.submit(new Runnable() {
@Override
public void run() {
final Bitmap bmp = downloadBitmap(url, width, height);
Message message = Message.obtain();
message.obj = bmp;

handler.sendMessage(message);
}
});
}

This code adds a new Runnable to the queue, which downloads the bitmap. Then it sends a message to a handler. A handler is used because all interactions with the UI have to be done in the UI thread. This means that we cannot directly set the image bitmap. A handler should be created in the thread the message will be handled in, so that's why we have to move the code outside of the Runnable anonymous class.

In handleMessage the bitmap is retrieved from msg.obj. The bitmap is only set if the current URL is the last one to be associated with the ImageView. If the download failed for some reason, a placeholder is used.

Conclusion

Full code
public enum BitmapManager {
INSTANCE;

private final Map<String, SoftReference<Bitmap>> cache;
private final ExecutorService pool;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
private Bitmap placeholder;

BitmapManager() {
cache = new HashMap<String, SoftReference<Bitmap>>();
}

public void setPlaceholder(Bitmap bmp) {
placeholder = bmp;
}

public Bitmap getBitmapFromCache(String url) {
if (cache.containsKey(url)) {
return cache.get(url).get();
}

return null;
}

public void queueJob(final String url, final ImageView imageView,
final int width, final int height) {
/* Create handler in UI thread. */
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
String tag = imageViews.get(imageView);
if (tag != null && tag.equals(url)) {
if (msg.obj != null) {
imageView.setImageBitmap((Bitmap) msg.obj);
} else {
imageView.setImageBitmap(placeholder);
Log.d(null, "fail " + url);
}
}
}
};

pool.submit(new Runnable() {
@Override
public void run() {
final Bitmap bmp = downloadBitmap(url, width, height);
Message message = Message.obtain();
message.obj = bmp;

handler.sendMessage(message);
}
});
}

public void loadBitmap(final String url, final ImageView imageView,
final int width, final int height) {
imageViews.put(imageView, url);
Bitmap bitmap = getBitmapFromCache(url);

// check in UI thread, so no concurrency issues
if (bitmap != null) {
Log.d(null, "Item loaded from cache: " + url);
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageBitmap(placeholder);
queueJob(url, imageView, width, height);
}
}

private Bitmap downloadBitmap(String url, int width, int height) {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
url).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
cache.put(url, new SoftReference<Bitmap>(bitmap));
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}
}



In case you're wondering, an enum is the preferred way to create a singleton class.

1. Great tutorial, really helped a lot. Thanks!

2. You're welcome! :)

3. Great tutorial.Thanks.I have a quesion.
Why does Map> cache not use Collections.synchronizedMap.

4. Great tutorial. Ive added a function to clear everything. Do you have a better solution ?

public void stop_it() {
pool.shutdownNow();
cache.clear();
}

Bit..INSTANCE.stop_it(); will be called in onDestroy method.

5. @jp: Good question! When I wrote the code I left it out because I didn't expect much problems with concurrency. However, when I look at my code again, I see that I do a containsKey and then a get. It could be possible that the download completes after the containsKey and before the get. This of course has a very low probability, but still, it's a small concurrency error.

@ledil: I would always keep the cache, because the Android OS automatically disposes of the cache if it's low on memory. If you only use the BitmapManager for a list, you could remove the singleton property by making it a normal class. Then you could make the BitmapManager a class variable of the List. When the list is destroyed, the whole manager is destroyed as well.

7. can you please share the sample code in the form of complete project
I am new in Android

8. why didn't you just use an asynctask?

9. @netpenthe: because I am using a fixed thread pool, which accepts runnables and callables.

10. can you please share the sample code in the form of complete project
I am new in Android (as piyush requested above)
With no idea what an Article would look like, I'm at a loss....

It's sooo easy for an iPhone app, it seems for android there's 100 ways and nobody does it the same.

11. This comment has been removed by the author.

12. If the queueJob method takes a WeakReference to the ImageView instead of a strong one(and checks for null appropriately) we can allow the ImageView to be garbage collected.

13. hi mate, thanks for the great tute. Could you add what your Article class looks like please, would help a lot.

Many Thanks

14. Hi Craig, the Article is a class that describes an RSS feed article. It has the following members:

private final String title;
private final String link;
private final String pubDate;
private final String author;
private String data;

and they all have getters.

15. great tutorial, thank you so much

16. Please don't forget to mention the original author who's code you reused http://stackoverflow.com/questions/541966/android-how-do-i-do-a-lazy-load-of-images-in-listview/3068012#3068012

17. I have used multiple sources for inspiration, though I can't remember copying large portions out of any of those. Much of the source code about this subject looks alike, so I understand why you see it this way.

Anyhow, your code looks good, and I can recommend a look at your poject to anyone who wants to see lazy loading in action.

18. Btw, I assume you're not referring to the stuff about the Runnable and ExecutorService because that was certainly my own idea. My post predates your commits about that.

19. I implemented this for my own customized ContactPicker with the following changes:
- not as a Singleton
- contactId instead of the url in the Map for imageViews
- loading a contact photo from the device instead of an image from the internet/url

Works good except that when rotating the device, sometimes (can take 10 attenpts) a contact that does not have a photo, a photo of another visible list item is shown. When a contact does not have a photo, I do not try to load it with BitmapManager, instead I directly set the placeholder bitmap.

Can't figure out how to solve this. Any idea?

20. Solved the problem by not using the Map imageViews at all, but directly use the Tag of the ImageView that is set in the getView method of the adapter.

Line 102 in your first listing is useless, because you never use the tag in your code.

21. hey good one thanks, but just want to ask when i first load my listview, the pics are not loaded up til i start to scroll, issit only me?

22. oh nvm fixed the prob coz i was using holder.iconView.getWidth() and .getHeight() to specify the width and height

23. i used this code because i wanted to recycle views. But there are times when the first row of the adapter shows a wrong image and returns to what it should be on a touch or any event tht refreshes the views.

24. This comment has been removed by the author.

25. Can this be used in MapView.?
i am Trying to Pin the Images in the Map

Source Code

for (int i = 0; i < ada.size(); i++) {
try {
AddressData tdUnit = td.get(i);

GeoPoint point = new GeoPoint(
(int) (Float.parseFloat(ada.get(i).latitude) * 1E6),
(int) (Float.parseFloat(ada.get(i).longitude) * 1E6));

Drawable d = new BitmapDrawable(ic.get(ada.get(i).brand_front_thumbnail));

d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());

overlayitem.setMarker(d);

} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), "No Network Connection", Toast.LENGTH_LONG).show();
}}

There are around 500 location in the API, it's Downloading around 6MB, processing & finally Plotting, this makes my Application Less Efficient. :(
How can the above code modified so that i get 10 Location Details , Then Plot it on the Map & Start over to the Next 10 & put this as a cycle until all the location is Plotted....

26. Thank you it's very helpfull for me

27. Great implementation! The best I've found so far...
But I've been struggling with an issue and it just won't work! The thing is that as soon as an ImageView(containing the already downloaded image) leaves the phone screen (e.g. because of scrolling) the placeholder-bitmap will take it's place again. This is a bit irritating, because when scrolling back (to the image before) you'll see first the placeholder-image which gets than replaced by the downloaded-img from our cache.
Might there be any possibility of avoiding this? So as soon as a placeholder-img. gets replaced by the downloaded one, it should stay somehow forever there(in the ImageView). Scrolling back/forth shouldn't affect this...
greets from AUT
George

28. I guess my description above wasn't clear enough, so I made a short screen cast to give you some visual-description.
You can clearly see how the images from my gallery "disappear" after scrolling back...I'm thinking about this issue for a while, and I'm still no sure how to improve/change this (i guess that's because of the SoftReference or WeakHashMap, but that's just a guess).
Greets from AUT
George

29. It could be the SoftReference if the images take up too much space in memory. What you could try is to download the images to the SD-card. Upon retrieval, you can check the cache first and if it doesn't exist, issue another download.

1. Thank you!
I just tested this and the cache gets cleared after some "random" time...although it does first record all Bitmaps(no matter how many!).
I will extend this code with some SD-card-cache strategies.

30. Thanks for this great and pretty clear tutorial!

31. Thank you,this is a great tutorial

32. Thank you very much it has helped me quite well....

33. Thanks I learn a lot of things from your blog.Now I am facing some problem.Please have a look that.
I uses this link.

I want add this map.put(“icon”, “icon: ” + e.getString(“icon”));

new String[] {“icon”, “name”, “vicinity” },
new int[] {R.id.imageview1, R.id.item_title, R.id.item_subtitle });
Please look this matter.I am hang over from this from last weeks.
How can i show this images.Please let me know.
Hope fully I can expect answer from you ASAP.
Thanks and Regards,
Maidul

34. Maidul, you have to create a class that stores all this information for each entry, in my example it's the Article class. Then you create an adapter very similar to my ListAdapter. Instead of URLS[position] you use article.getIcon() to get the location;

35. Thanks a lot, This really helped me out

36. Hello,

Thank you, for the code, I am having another issue,
I am using this code with custom adapter extends from cursor adapter, It has bindView method which calls multiple times and this code try to download single image multiple times.

Kindly suggest me how to prevent BitmapManager to download image multiple times.

Thank You,

37. I have spent about 5 hours trying to do a better lazy loading, thx for the help.

38. Bravo and nothing else.

Many many thanks

39. i retrived images from url i got error "java.io.IOException: BufferedInputStream is closed" and also "at org.apache.harmony.luni.internal.net.www.protocol.http.UnknownLengthHttpInputStream.available(UnknownLengthHttpInputStream.java:52"

if there any solution please give me...

40. Thanks, this is the best implementation on this topic I've found so far.
Helped me a lot. Appreciated! :)

41. how can i save captured image to sd card

42. Great tutorial, thanks a lot!

43. Thanks a lot! Do this in iphone is easy for me, but here is a bit more difficult (at least for me at all xD), you hellp me a lot!! cheers

44. thank you man.. your code helped me .. thank you very much:

45. how to retrieve images and its retaled heading from rss-feed and show it in listview in android?????

46. Excellent write up. I found gold reading your blog content, many things I found here amaze me. Good work you guys.

47. I've been coding for years but just started playing with Android. This was extremely helpful. Thanks for taking the time to share.

48. thanks for share,but when i srcoll down listview, after that i srcoll up again some item loaded it was lost and must have some time to load it again.

how to fix it !!!

49. Thank you, Ben. You have saved me! I was not able to load the images. I reached here from http://stackoverflow.com/questions/541966/how-do-i-do-a-lazy-load-of-images-in-listview. Thank you!

50. But when I scroll down and up the listview,the picture's location is wrong.

51. Can I call this from an async task?