views:

39

answers:

2

I have a GridView, in my activity, that displays about 30 thumbnails fetched from a remote server. I am doing 2-level caching for the images:

  1. there is an in-memory cache(HashMap using softReferences)
  2. Secondly, all the images fetched are written to Sdcard(so as to avoid refetches when in-memory bitmaps are GC'd).

From the getView of the GridView-Adapter, I call getCachedImage function of the Cache class, which will either return a default image or an image from one of the caches. When a default image is returned, the Cache class starts a AsyncTask to fetch the image from the remote server. This image is then also written to both the caches.

The problem is: When the AsyncTask finishes, I want it to also update the UI alongwith the caches. I tried passing the instance of the GridView child(ImageView) to the AsyncTask and then setting the image of this child view, in the postExecute of the AsyncTask but due to View recycling, this approach results in incorrect images in incorrect views, if the fetches take long time.

What are the ways in which i can make my AsyncTask more proactive meaning it should let the UI know that image download has finished?
Thanks!

+1  A: 

The approach I took with CWAC-Thumbnail is to do everything you did, but also stick the URL presently being displayed by an ImageView in that ImageView object's tag via setTag(). Then, when the AsyncTask ends, I check the tag to see if the URL of the ImageView matches the URL the task downloaded. If they do, I apply the image. If not, I don't.

CommonsWare
I tried to work the tag magic earlier albeit without the additional checks that you've mentioned. I was getting wierd NullPointerExceptions. I think, I would add your suggestion and see what happens.
Samuh
update: okay, I made the aforementioned checks and re-run my application, I was still getting NullPointerException. Something made me uninstall the application and reinstall it again. Now, there are no NullPointerExceptions! Strange indeed. I use Eclipse with ADT.As for the cache impln, thanks for your advice(and the project link); it worked like a charm!
Samuh
A: 

A way to handle this case is to simply write a Custom Image View (which inherits of ImageView) that is able to deal with all this stuff by itself.

Then you can just put your Custom image Views wherever you need it and just call something like "startLoading" on it. In this "startLoading", just put the logic you described.

Fabien