views:

140

answers:

4

I have a ListView with custom ArrayAdapter. Each of the row in this ListView has an icon and some text. These icons are downloaded in background,cached and then using a callback, substituted in their respective ImageViews. The logic to get a thumbnail from cache or download is triggered every time getView() runs.

Now, according to Romain Guy:

"there is absolutely no guarantee on the order in which getView() will be called nor how many times."

I have seen this happen, for a row of size two getView() was being called six times!

How do I change my code to avoid duplicate thumbnail-fetch-requests and also handle view recycling?

Thanks.

A: 

From api.

public abstract View   getView  (int position, View  convertView, 
                                 ViewGroup  parent)

convertView - The old view to reuse, if possible. Note: You should check that this view is non-null and of an appropriate type before using. If it is not possible to convert this view to display the correct data, this method can create a new view.

So if getView has already been called for this specific index then convertView will be the View object that was returned from that first call.

You can do something like.

if(!(convertView instanceof ImageView)){
   convertView = new ImageView();
   //get image from whereever
} else {} // ImageView already created
BrennaSoft
A: 

The better would be to create a object with Thumbnail(bitmap) and the text. And read the thumbnail if its not available in the object.

Karan
A: 

Create an array of ImageView objects in your adapter and cache them as you retrive them (whether from cache or web). For example, in getView, before you fetch the ImageView, check if it's already in your local array, if so, use it, if not fetch, once received store in your local ImageView array for future use.

Ricardo Villamil
A: 

Exactly, that could happen for example when you have

android:layout_height="wrap_content"

in your ListView definition. Changing it to fill_parent would avoid it.

jBilbo
It does not completely evict the redundant call problem; but it helps measure the height of the ListView better. And if the height is measured correctly, ListView can correctly determine the number of rows currently visible which could reduce the number of redundant getView() calls.
Samuh