blob: 2f6f1f926c192dcc59dd9afbe7e2a5711774f843 [file] [log] [blame]
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;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class JSONImageListAdapter extends ArrayAdapter<JSONImageItem> {
private final Handler mHandler;
private final BlockingQueue<JSONImageItem> mItemQueue;
private final HashMap<JSONImageItem,SoftReference<Drawable>> mCache;
private boolean mWorking = true;
public JSONImageListAdapter(Context ctx) {
super(ctx, 0, 0);
mCache = new HashMap<JSONImageItem,SoftReference<Drawable>>();
mItemQueue = new LinkedBlockingQueue<JSONImageItem>();
mHandler = new Handler();
new Thread(mDownloader).start();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
imageView = new ImageView(getContext());
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
JSONImageItem jso = getItem(position);
SoftReference<Drawable> 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<Drawable>(d));
}
imageView.setImageDrawable(d);
} else {
imageView.setImageResource(R.drawable.image_loading);
}
return imageView;
}
@Override
public void add(JSONImageItem jso) {
super.add(jso);
mItemQueue.add(jso);
}
public void setLastItem() {
mWorking = false;
}
private void downloadAndDisplay(JSONImageItem jsi) {
final Drawable d = jsi.getThumnail();
if ( d != null ) {
mCache.put(jsi, new SoftReference<Drawable>(d));
mHandler.post(new Runnable() {
public void run() {
notifyDataSetChanged();
}
});
}
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() {
public void run() {
while ( mWorking || !mItemQueue.isEmpty()) {
try {
JSONImageItem jsi = mItemQueue.take();
downloadAndDisplay(jsi);
} catch (Exception e) {
Log.e(LinaroConnect.TAG, "error getting image", e);
}
}
}
};
}