I am making an android application where there are news articles with a thumbnail. Those thumbnails are loaded from network and stored in a LruCache with the URL as the key, and the bitmap as the value.
private LruCache<String, Bitmap> tCache;
in the getView() method of the adapter, I call getThumbnail() which checks the cache (load from network when necessary) then show the thumbnail.
public void populateList(){
...
new Thread(new Runnable() {
@Override
public void run() {
getThumbnail(story, thumbnail);
}
}).start();
}
and
private Bitmap getThumbnail(Story story, ImageView imageView) {
String url = story.getThumbnail();
Bitmap bitmap;
synchronized (tCache) {
bitmap = tCache.get(url);
if (bitmap == null) {
bitmap = new ImageLoadingUtils(this, imageView).execute(url,
Boolean.TRUE).get();
tCache.put(url, bitmap);
}
}
return bitmap;
}
The ImageLoadingUtils loads from network and puts the resulting bitmap in the ImageView when done.
@Override
protected void onPostExecute(Bitmap result) {
if (imageView != null) {
imageView.setImageBitmap(result);
adapter.notifyDataSetChanged();
}
}
The problem is the thumbnails get repeated in the same ListView when I scroll down.
________ |IMAGE1| |IMAGE2| |IMAGE3| SCREEN |IMAGE4| -------- |IMAGE1| |IMAGE2| OFFSCREEN ________
And the articles don't have the correct thumbnails anymore when I scroll down then back up. It's very messed up.
Anyone can spot the issue? Thank you a lot.
The problem is because the Views are reused in a listview. Here is a good example on how to cache and load thumbnails asynchronously in listview.