st_dec
st_dec

Reputation: 152

How to use Picasso with listview?

I want to add to ListView information about widgets:

public class Widget {
    String w_type;
    String title;
    String desc;
    String img;
//....
}

I want to show image in listview if img field isn't empty. How should I do it using Picasso without duplicating ang showing wrong images in ListView after scrolling? This is current code of getView method from my adapter for listview:

public View getView(int i, View someView, ViewGroup arg2) {
    LayoutInflater inflater = LayoutInflater.from(context);
    if (someView == null) {
        someView = inflater.inflate(R.layout.widgets_list, arg2, false);
    }

    ImageView img = (ImageView) someView.findViewById(R.id.pic);

    String img_url = data.get(i).img;
    if (!img_url.equals("")){ 
        Picasso.with(context).load(img_url).into(img);
    }
    return someView;
}

But now ListView shows wrong and duplicates images. How can I fix it?

Upvotes: 3

Views: 4660

Answers (1)

JozeRi
JozeRi

Reputation: 3429

I would recommend using the ViewHolder pattern. more information can be found here :

https://developer.android.com/training/improving-layouts/smooth-scrolling.html

take note that you do have to handle a case where your img_url is indeed empty, you need to set a default image for that case, if not, when that cell is recycled the image will remain unchanged and then you will experience that duplication you were talking about.

example code below :

@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {

  ViewHolder holder;

  if (convertView == null) {
    convertView = LayoutInflater.from(mContext).inflate(R.layout.widgets_list, null);
    holder = new ViewHolder();
    holder.mImageView = (ImageView) convertView.findViewById(R.id.iconImageView);
    convertView.setTag(holder);
  } else {
    holder = (ViewHolder) convertView.getTag();
  }

  //fetching your data object with the current position
  Example example = mExamples[position];

  String img_url = example.get(i).img;

  if (!img_url.equals("")){
    Picasso.with(context).load(img_url).into(holder.mImageView);
  } else {
    //todo - implement a default image in case img_url is indeed empty
    Picasso.with(context).load(defaultImage).into(holder.mImageView);
  }

  return convertView;
}

private static class ViewHolder {
  ImageView mImageView;
}

Upvotes: 1

Related Questions