Lazy loading of images in Listview

http://negativeprobability.blogspot.com/2011/08/lazy-loading-of-images-in-listview.html


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.

  1. public class ListAdapter extends ArrayAdapter<Article> {  
  2.     private List<Article> articles;  
  3.     private Context context;  
  4.     private final LayoutInflater inflator;  
  5.   
  6.     private static final String[] URLS = {  
  7.             "http://lh5.ggpht.com/_mrb7w4gF8Ds/TCpetKSqM1I/AAAAAAAAD2c/Qef6Gsqf12Y/s144-c/_DSC4374%20copy.jpg",  
  8.             "http://lh5.ggpht.com/_Z6tbBnE-swM/TB0CryLkiLI/AAAAAAAAVSo/n6B78hsDUz4/s144-c/_DSC3454.jpg",  
  9.             "http://lh3.ggpht.com/_GEnSvSHk4iE/TDSfmyCfn0I/AAAAAAAAF8Y/cqmhEoxbwys/s144-c/_MG_3675.jpg",  
  10.             "http://lh6.ggpht.com/_Nsxc889y6hY/TBp7jfx-cgI/AAAAAAAAHAg/Rr7jX44r2Gc/s144-c/IMGP9775a.jpg",  
  11.             "http://lh3.ggpht.com/_lLj6go_T1CQ/TCD8PW09KBI/AAAAAAAAQdc/AqmOJ7eg5ig/s144-c/Juvenile%20Gannet%20despute.jpg",  
  12.             "http://lh6.ggpht.com/_ZN5zQnkI67I/TCFFZaJHDnI/AAAAAAAABVk/YoUbDQHJRdo/s144-c/P9250508.JPG",  
  13.             "http://lh4.ggpht.com/_XjNwVI0kmW8/TCOwNtzGheI/AAAAAAAAC84/SxFJhG7Scgo/s144-c/0014.jpg",  
  14.             "http://lh6.ggpht.com/_lnDTHoDrJ_Y/TBvKsJ9qHtI/AAAAAAAAG6g/Zll2zGvrm9c/s144-c/000007.JPG",  
  15.             "http://lh6.ggpht.com/_qvCl2efjxy0/TCIVI-TkuGI/AAAAAAAAOUY/vbk9MURsv48/s144-c/DSC_0844.JPG",  
  16.             "http://lh4.ggpht.com/_4f1e_yo-zMQ/TCe5h9yN-TI/AAAAAAAAXqs/8X2fIjtKjmw/s144-c/IMG_1786.JPG",  
  17.             "http://lh6.ggpht.com/_iFt5VZDjxkY/TB9rQyWnJ4I/AAAAAAAADpU/lP2iStizJz0/s144-c/DSCF1014.JPG",  
  18.             "http://lh5.ggpht.com/_hepKlJWopDg/TB-_WXikaYI/AAAAAAAAElI/715k4NvBM4w/s144-c/IMG_0075.JPG",  
  19.             "http://lh6.ggpht.com/_OfRSx6nn68g/TCzsQic_z3I/AAAAAAABOOI/5G4Kwzb2qhk/s144-c/EASTER%20ISLAND_Hanga%20Roa_31.5.08_46.JPG",  
  20.             "http://lh6.ggpht.com/_ZGv_0FWPbTE/TB-_GLhqYBI/AAAAAAABVxs/cVEvQzt0ke4/s144-c/IMG_1288_hf.jpg",  
  21.             "http://lh6.ggpht.com/_a29lGRJwo0E/TBqOK_tUKmI/AAAAAAAAVbw/UloKpjsKP3c/s144-c/31012332.jpg",  
  22.             "http://lh3.ggpht.com/_55Lla4_ARA4/TB6xbyxxJ9I/AAAAAAABTWo/GKe24SwECns/s144-c/Bluebird%20049.JPG",  
  23.             "http://lh3.ggpht.com/_iVnqmIBYi4Y/TCaOH6rRl1I/AAAAAAAA1qg/qeMerYQ6DYo/s144-c/Kwiat_100626_0016.jpg",  
  24.             "http://lh6.ggpht.com/_QFsB_q7HFlo/TCItd_2oBkI/AAAAAAAAFsk/4lgJWweJ5N8/s144-c/3705226938_d6d66d6068_o.jpg",  
  25.             "http://lh5.ggpht.com/_JTI0xxNrKFA/TBsKQ9uOGNI/AAAAAAAChQg/z8Exh32VVTA/s144-c/CRW_0015-composite.jpg",  
  26.             "http://lh6.ggpht.com/_loGyjar4MMI/S-InVNkTR_I/AAAAAAAADJY/Fb5ifFNGD70/s144-c/Moving%20Rock.jpg",  
  27.             "http://lh4.ggpht.com/_L7i4Tra_XRY/TBtxjScXLqI/AAAAAAAAE5o/ue15HuP8eWw/s144-c/opera%20house%20II.jpg",  
  28.             "http://lh3.ggpht.com/_rfAz5DWHZYs/S9cstBTv1iI/AAAAAAAAeYA/EyZPUeLMQ98/s144-c/DSC_6425.jpg",  
  29.             "http://lh6.ggpht.com/_iGI-XCxGLew/S-iYQWBEG-I/AAAAAAAACB8/JuFti4elptE/s144-c/norvig-polar-bear.jpg",  
  30.             "http://lh3.ggpht.com/_M3slUPpIgmk/SlbnavqG1cI/AAAAAAAACvo/z6-CnXGma7E/s144-c/mf_003.jpg",  
  31.             "http://lh4.ggpht.com/_loGyjar4MMI/S-InQvd_3hI/AAAAAAAADIw/dHvCFWfyHxQ/s144-c/Rainbokeh.jpg",  
  32.             "http://lh4.ggpht.com/_yy6KdedPYp4/SB5rpK3Zv0I/AAAAAAAAOM8/mokl_yo2c9E/s144-c/Point%20Reyes%20road%20.jpg",  
  33.             "http://lh5.ggpht.com/_6_dLVKawGJA/SMwq86HlAqI/AAAAAAAAG5U/q1gDNkmE5hI/s144-c/mobius-glow.jpg",  
  34.             "http://lh3.ggpht.com/_QFsB_q7HFlo/TCItc19Jw3I/AAAAAAAAFs4/nPfiz5VGENk/s144-c/4551649039_852be0a952_o.jpg",  
  35.             "http://lh6.ggpht.com/_TQY-Nm7P7Jc/TBpjA0ks2MI/AAAAAAAABcI/J6ViH98_poM/s144-c/IMG_6517.jpg",  
  36.             "http://lh3.ggpht.com/_rfAz5DWHZYs/S9cLAeKuueI/AAAAAAAAeYU/E19G8DOlJRo/s144-c/DSC_4397_8_9_tonemapped2.jpg",  
  37.             "http://lh4.ggpht.com/_TQY-Nm7P7Jc/TBpi6rKfFII/AAAAAAAABbg/79FOc0Dbq0c/s144-c/david_lee_sakura.jpg",  
  38.             "http://lh3.ggpht.com/_TQY-Nm7P7Jc/TBpi8EJ4eDI/AAAAAAAABb0/AZ8Cw1GCaIs/s144-c/Hokkaido%20Swans.jpg",  
  39.             "http://lh3.ggpht.com/_1aZMSFkxSJI/TCIjB6od89I/AAAAAAAACHM/CLWrkH0ziII/s144-c/079.jpg",  
  40.             "http://lh5.ggpht.com/_loGyjar4MMI/S-InWuHkR9I/AAAAAAAADJE/wD-XdmF7yUQ/s144-c/Colorado%20River%20Sunset.jpg",  
  41.             "http://lh3.ggpht.com/_0YSlK3HfZDQ/TCExCG1Zc3I/AAAAAAAAX1w/9oCH47V6uIQ/s144-c/3138923889_a7fa89cf94_o.jpg",  
  42.             "http://lh6.ggpht.com/_K29ox9DWiaM/TAXe4Fi0xTI/AAAAAAAAVIY/zZA2Qqt2HG0/s144-c/IMG_7100.JPG",  
  43.             "http://lh6.ggpht.com/_0YSlK3HfZDQ/TCEx16nJqpI/AAAAAAAAX1c/R5Vkzb8l7yo/s144-c/4235400281_34d87a1e0a_o.jpg",  
  44.             "http://lh4.ggpht.com/_8zSk3OGcpP4/TBsOVXXnkTI/AAAAAAAAAEo/0AwEmuqvboo/s144-c/yosemite_forrest.jpg",  
  45.             "http://lh4.ggpht.com/_6_dLVKawGJA/SLZToqXXVrI/AAAAAAAAG5k/7fPSz_ldN9w/s144-c/coastal-1.jpg",  
  46.             "http://lh4.ggpht.com/_WW8gsdKXVXI/TBpVr9i6BxI/AAAAAAABhNg/KC8aAJ0wVyk/s144-c/IMG_6233_1_2-2.jpg",  
  47.             "http://lh3.ggpht.com/_loGyjar4MMI/S-InS0tJJSI/AAAAAAAADHU/E8GQJ_qII58/s144-c/Windmills.jpg",  
  48.             "http://lh4.ggpht.com/_loGyjar4MMI/S-InbXaME3I/AAAAAAAADHo/4gNYkbxemFM/s144-c/Frantic.jpg",  
  49.             "http://lh5.ggpht.com/_loGyjar4MMI/S-InKAviXzI/AAAAAAAADHA/NkyP5Gge8eQ/s144-c/Rice%20Fields.jpg",  
  50.             "http://lh3.ggpht.com/_loGyjar4MMI/S-InZA8YsZI/AAAAAAAADH8/csssVxalPcc/s144-c/Seahorse.jpg",  
  51.             "http://lh3.ggpht.com/_syQa1hJRWGY/TBwkCHcq6aI/AAAAAAABBEg/R5KU1WWq59E/s144-c/Antelope.JPG",  
  52.             "http://lh5.ggpht.com/_MoEPoevCLZc/S9fHzNgdKDI/AAAAAAAADwE/UAno6j5StAs/s144-c/c84_7083.jpg",  
  53.             "http://lh4.ggpht.com/_DJGvVWd7IEc/TBpRsGjdAyI/AAAAAAAAFNw/rdvyRDgUD8A/s144-c/Free.jpg",  
  54.             "http://lh6.ggpht.com/_iO97DXC99NY/TBwq3_kmp9I/AAAAAAABcz0/apq1ffo_MZo/s144-c/IMG_0682_cp.jpg",  
  55.             "http://lh4.ggpht.com/_7V85eCJY_fg/TBpXudG4_PI/AAAAAAAAPEE/8cHJ7G84TkM/s144-c/20100530_120257_0273-Edit-2.jpg" };  
  56.   
  57.     private static class ViewHolder {  
  58.         public ImageView iconView;  
  59.         public TextView nameTextView;  
  60.         public TextView bottomText;  
  61.     }  
  62.   
  63.     public ListAdapter(Context context, int textViewResourceId,  
  64.             List<Article> articles) {  
  65.         super(context, textViewResourceId, articles);  
  66.         this.articles = articles;  
  67.         this.context = context;  
  68.         inflator = (LayoutInflater) context  
  69.                 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  70.   
  71.         BitmapManager.INSTANCE.setPlaceholder(BitmapFactory.decodeResource(  
  72.                 context.getResources(), R.drawable.icon));  
  73.     }  
  74.   
  75.     @Override  
  76.     public View getView(int position, View convertView, ViewGroup parent) {  
  77.         ViewHolder holder;  
  78.   
  79.         if (convertView == null) {  
  80.             convertView = inflator.inflate(R.layout.article_row, null);  
  81.   
  82.             TextView nameTextView = (TextView) convertView  
  83.                     .findViewById(R.id.title);  
  84.             TextView bottomText = (TextView) convertView  
  85.                     .findViewById(R.id.bottomtext);  
  86.             ImageView iconView = (ImageView) convertView  
  87.                     .findViewById(R.id.article_icon);  
  88.             holder = new ViewHolder();  
  89.             holder.nameTextView = nameTextView;  
  90.             holder.bottomText = bottomText;  
  91.             holder.iconView = iconView;  
  92.             convertView.setTag(holder);  
  93.         } else {  
  94.             holder = (ViewHolder) convertView.getTag();  
  95.         }  
  96.   
  97.         Article article = articles.get(position);  
  98.         holder.nameTextView.setText(article.getTitle());  
  99.         holder.bottomText.setText(article.getAuthor() + " | "  
  100.                 + article.getPubDate());  
  101.   
  102.         holder.iconView.setTag(URLS[position]);  
  103.         BitmapManager.INSTANCE.loadBitmap(URLS[position], holder.iconView, 32,  
  104.                 32);  
  105.   
  106.         return convertView;  
  107.     }  
  108. }  

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.

Downloading the bitmaps
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:

  1. private Bitmap downloadBitmap(String url, int width, int height) {  
  2.         try {  
  3.             Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(  
  4.                     url).getContent());  
  5.             bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);  
  6.             cache.put(url, new SoftReference<Bitmap>(bitmap));  
  7.             return bitmap;  
  8.         } catch (MalformedURLException e) {  
  9.             e.printStackTrace();  
  10.         } catch (IOException e) {  
  11.             e.printStackTrace();  
  12.         }  
  13.   
  14.         return null;  
  15.     }  
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
  1. public void loadBitmap(final String url, final ImageView imageView,  
  2.         final int width, final int height) {  
  3.     imageViews.put(imageView, url);  
  4.     Bitmap bitmap = getBitmapFromCache(url);  
  5.   
  6.     // check in UI thread, so no concurrency issues  
  7.     if (bitmap != null) {  
  8.         Log.d(null"Item loaded from cache: " + url);  
  9.         imageView.setImageBitmap(bitmap);  
  10.     } else {  
  11.         imageView.setImageBitmap(placeholder);  
  12.         queueJob(url, imageView, width, height);  
  13.     }  
  14. }  
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.

The working thread
All that's left now is to call the downloadBitmap function from a new thread. Most code I saw online just spawns a new thread, but that can become very inefficient. Imagine that the Listview contains 500 items: that would mean that 500 threads would be spawned! Instead, we use the  ExecutorService class from the Java Concurrency framework. We create a fixed thread pool ( newFixedThreadPool) with 5 items (this number is arbitrary, I haven't tested which amount is optimal), which means that there will be up to five images that are downloaded at the same time. All the other downloads are stored in an unbounded queue.

  1. public void queueJob(final String url, final ImageView imageView,  
  2.             final int width, final int height) {  
  3.         /* Create handler in UI thread. */  
  4.         final Handler handler = new Handler() {  
  5.             @Override  
  6.             public void handleMessage(Message msg) {  
  7.                 String tag = imageViews.get(imageView);  
  8.                 if (tag != null && tag.equals(url)) {  
  9.                     if (msg.obj != null) {  
  10.                         imageView.setImageBitmap((Bitmap) msg.obj);  
  11.                     } else {  
  12.                         imageView.setImageBitmap(placeholder);  
  13.                         Log.d(null"fail " + url);  
  14.                     }  
  15.                 }  
  16.             }  
  17.         };  
  18.   
  19.         pool.submit(new Runnable() {  
  20.             @Override  
  21.             public void run() {  
  22.                 final Bitmap bmp = downloadBitmap(url, width, height);  
  23.                 Message message = Message.obtain();  
  24.                 message.obj = bmp;  
  25.                 Log.d(null"Item downloaded: " + url);  
  26.   
  27.                 handler.sendMessage(message);  
  28.             }  
  29.         });  
  30.     }  
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
And there you have it. We've made a lazy loading bitmap manager that works with recycled listviews. Some things could be done to improve performance even more, for example cancelling downloads if the view is destroyed and preventing downloading the same file at the same time. Anyhow, if you found this tutorial helpful, please leave a message :)


Full code
  1. public enum BitmapManager {  
  2.     INSTANCE;  
  3.   
  4.     private final Map<String, SoftReference<Bitmap>> cache;  
  5.     private final ExecutorService pool;  
  6.     private Map<ImageView, String> imageViews = Collections  
  7.             .synchronizedMap(new WeakHashMap<ImageView, String>());  
  8.     private Bitmap placeholder;  
  9.   
  10.     BitmapManager() {  
  11.         cache = new HashMap<String, SoftReference<Bitmap>>();  
  12.         pool = Executors.newFixedThreadPool(5);  
  13.     }  
  14.   
  15.     public void setPlaceholder(Bitmap bmp) {  
  16.         placeholder = bmp;  
  17.     }  
  18.   
  19.     public Bitmap getBitmapFromCache(String url) {  
  20.         if (cache.containsKey(url)) {  
  21.             return cache.get(url).get();  
  22.         }  
  23.   
  24.         return null;  
  25.     }  
  26.   
  27.     public void queueJob(final String url, final ImageView imageView,  
  28.             final int width, final int height) {  
  29.         /* Create handler in UI thread. */  
  30.         final Handler handler = new Handler() {  
  31.             @Override  
  32.             public void handleMessage(Message msg) {  
  33.                 String tag = imageViews.get(imageView);  
  34.                 if (tag != null && tag.equals(url)) {  
  35.                     if (msg.obj != null) {  
  36.                         imageView.setImageBitmap((Bitmap) msg.obj);  
  37.                     } else {  
  38.                         imageView.setImageBitmap(placeholder);  
  39.                         Log.d(null"fail " + url);  
  40.                     }  
  41.                 }  
  42.             }  
  43.         };  
  44.   
  45.         pool.submit(new Runnable() {  
  46.             @Override  
  47.             public void run() {  
  48.                 final Bitmap bmp = downloadBitmap(url, width, height);  
  49.                 Message message = Message.obtain();  
  50.                 message.obj = bmp;  
  51.                 Log.d(null"Item downloaded: " + url);  
  52.   
  53.                 handler.sendMessage(message);  
  54.             }  
  55.         });  
  56.     }  
  57.   
  58.     public void loadBitmap(final String url, final ImageView imageView,  
  59.             final int width, final int height) {  
  60.         imageViews.put(imageView, url);  
  61.         Bitmap bitmap = getBitmapFromCache(url);  
  62.   
  63.         // check in UI thread, so no concurrency issues  
  64.         if (bitmap != null) {  
  65.             Log.d(null"Item loaded from cache: " + url);  
  66.             imageView.setImageBitmap(bitmap);  
  67.         } else {  
  68.             imageView.setImageBitmap(placeholder);  
  69.             queueJob(url, imageView, width, height);  
  70.         }  
  71.     }  
  72.   
  73.     private Bitmap downloadBitmap(String url, int width, int height) {  
  74.         try {  
  75.             Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(  
  76.                     url).getContent());  
  77.             bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);  
  78.             cache.put(url, new SoftReference<Bitmap>(bitmap));  
  79.             return bitmap;  
  80.         } catch (MalformedURLException e) {  
  81.             e.printStackTrace();  
  82.         } catch (IOException e) {  
  83.             e.printStackTrace();  
  84.         }  
  85.   
  86.         return null;  
  87.     }  
  88. }  

In case you're wondering, an enum is the preferred way to create a singleton class.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值