Samuh
Samuh

Reputation: 36484

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

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!

Upvotes: 1

Views: 218

Answers (2)

Fabien Devos
Fabien Devos

Reputation: 1

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.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006799

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.

Upvotes: 3

Related Questions