Android – What are the ways to get a handle on the view amidst recycling

androidcachinglistviewperformance

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!

Best Answer

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.