From 99f3bbc2e8983c940cb95d0c114874176985ced7 Mon Sep 17 00:00:00 2001 From: Andy Doan Date: Fri, 30 Sep 2011 15:58:47 -0500 Subject: fix async image logic This was done completely wrong. The view will recycle the individual view at will, so you can't keep a map of them like we had. instead, use a SoftReference cache of the drawables so that we can display them quickly when possible --- src/org/linaro/connect/JSONImageListAdapter.java | 36 +++++++++++++++++------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/src/org/linaro/connect/JSONImageListAdapter.java b/src/org/linaro/connect/JSONImageListAdapter.java index ab02307..8c2715d 100644 --- a/src/org/linaro/connect/JSONImageListAdapter.java +++ b/src/org/linaro/connect/JSONImageListAdapter.java @@ -1,11 +1,13 @@ package org.linaro.connect; +import java.lang.ref.SoftReference; import java.util.HashMap; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import android.content.Context; import android.graphics.drawable.Drawable; +import android.os.Handler; import android.util.Log; import android.view.View; import android.view.ViewGroup; @@ -15,16 +17,18 @@ import android.widget.ImageView; public class JSONImageListAdapter extends ArrayAdapter { + private final Handler mHandler; private final BlockingQueue mItemQueue; - private final HashMap mItemMap; + private final HashMap> mCache; private boolean mWorking = true; public JSONImageListAdapter(Context ctx) { super(ctx, 0, 0); - mItemMap = new HashMap(); + mCache = new HashMap>(); mItemQueue = new LinkedBlockingQueue(); + mHandler = new Handler(); new Thread(mDownloader).start(); } @@ -41,10 +45,19 @@ public class JSONImageListAdapter extends ArrayAdapter { imageView = (ImageView) convertView; } - imageView.setImageResource(R.drawable.image_loading); - JSONImageItem jso = getItem(position); - mItemMap.put(jso, imageView); + SoftReference ref = mCache.get(jso); + if( ref != null ) { + Drawable d = ref.get(); + if( d == null ) { //we've been garbage collected, read from cache + d = jso.getThumnail(); + mCache.put(jso, new SoftReference(d)); + } + + imageView.setImageDrawable(d); + } else { + imageView.setImageResource(R.drawable.image_loading); + } return imageView; } @@ -60,16 +73,19 @@ public class JSONImageListAdapter extends ArrayAdapter { private void downloadAndDisplay(JSONImageItem jsi) { final Drawable d = jsi.getThumnail(); - final ImageView iv = mItemMap.get(jsi); - if( d != null && iv != null ) - iv.post(new Runnable() { + if ( d != null ) { + mCache.put(jsi, new SoftReference(d)); + mHandler.post(new Runnable() { @Override public void run() { - iv.setImageDrawable(d); + notifyDataSetChanged(); } }); - else + } + else { Log.e(LinaroConnect.TAG, "null jso or view in image list"); + mItemQueue.add(jsi); //try again for later + } } private final Runnable mDownloader = new Runnable() { -- cgit v1.2.3