BaseAdapter and Picasso issue

有些话、适合烂在心里 提交于 2019-12-02 14:01:00

问题


I am having a problem loading images in ListView from a server with Picasso.

I have a BaseAdapter that is used to fill my ListView. In this ListView some items have an image and some not.

in this method:

public View getView(final int position, View convertView, ViewGroup parent) {

I do:

 ...

//context = Activity context;
//context1 = Context context1;
context1 = context.getApplicationContext();

 if (!photo[position].equals("")) {

    String stringurl = "http://www.blablabla.it/img/"+photo[position]+".jpg";

    Picasso.with(context1)
           .load(stringurl)
           .placeholder(R.drawable.white)
           .into(holder.imageD);
        }
 else {

    holder.imageD.setImageBitmap(null);
 }

This code work, but too often I see that an image is in a different place than where it belongs!

as you can imagine this is very annoying for users .. Thanks everybody


回答1:


You had faced this problem becuase ListView recycle items view + Picasso calls are asynchronous ... How it can appears?

  1. You start loading with Picasso
  2. View is reused (convertView != null)
  3. You are setting holder.imageD.setImageBitmap(null);
  4. Asynchronous from point 1. is finnished

Thats why you are having wrong image loaded ...

To avoid such behaviour you need to inform Picasso loader to cancel previous request. So instead just setting image bitmap to null you have to set it via Picasso library (in else statment use):

Picasso.with(context1).load(null).placeholder(R.drawable.white).into(holder.imageD);

edit: following @Budius comments: even better solution will be cancel and set instead like:

{
  Picasso.with(context1).cancelRequest(holder.imageD);
  //holder.imageD.setImageBitmap(null); //or
  holder.imageD.setImageResource(R.drawable.white); //depends on your needs
}

This should be more efficent way as it should creates less internal objects on every getView calls.



来源:https://stackoverflow.com/questions/28275637/baseadapter-and-picasso-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!