I have a ListView which contains an ImageView and a TextView. I'm subclassing ArrayAdapter so that I can load an image from the internet, via a subclassed AsyncTask. All good so far.
The problem is that if I try to use convertView, I have a problem where the image is recycled briefly into the wrong row. (This is a company's logo, so this is... not good.)
If I don't use convertView, however, the image is lost when the user scrolls. So if they scroll down and back up, the image is re-loaded from the internet (which is obviously bad for data use, battery life etc.)
Is there a simple way to fix this so that it doesn't load from the internet each time, or move the images around?
Here's what I'm using so far:
public class SupplierAdapter extends ArrayAdapter<Supplier>{
int resource;
String response;
Context context;
public SupplierAdapter(Context context, int resource, List<Supplier> suppliers) {
super(context, resource, suppliers);
this.resource = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
LinearLayout view;
Supplier s = getItem(position);
if(convertView == null){
view = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi;
vi = (LayoutInflater) getContext().getSystemService(inflater);
vi.inflate(resource, view, true);
} else {
view = (LinearLayout) convertView;
}
ImageView iv = (ImageView) view.findViewById(R.id.thumbnail);
// s.getThumbnail returns a URL
new DownloadImageTask(iv).execute(s.getThumbnail());
TextView titleText =(TextView) view.findViewById(R.id.titleText);
titleText.setText(s.getTitle());
titleText.setTag(s.getId());
return view;
}
}
All help very much appreciated :)
John, try using raptureinvenice.com's WebImageView. I recently refactored my code to use this easy and lightweight library and so far, so good. It easily provides a two level cache, updates multiple targets simultaneously, and was incredibly easy to set up. It looks like it seems to drop about 1/20 requests to display an image. Other than this lurking bug that could be the library's fault, it is excellent.