Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load multiple images with picasso - Android

I am trying to load multiple images from some urls using picasso library.

So far I have tried this code:

 for(int i = 0; i < friends.size(); i++)
   {
       final Profile profile = friends.get(i);
       String url = profile.getUserImageUrl();


       Picasso.with(getContext()).load(url).into(new Target() {
           // It doesn't reach any of the code below ....!! 

           @Override
           public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)    {
               profile.setUserImage(bitmap);
               counter++;

               if(counter >= friends.size() - 1)
                   cards();
           }

           @Override
           public void onBitmapFailed(Drawable drawable) {
               Log.e("App", "Failed to load company logo in onBitmapFailed method");
           }

           @Override
           public void onPrepareLoad(Drawable drawable) {
               Log.e("App","Failed to load company logo in onBitmapFailed method");
           }

       });
   }

This code doesn't work. When I run this code it doesn't reach to any line within the Target interface. Someone have any ideas for why?


1 Answers

You just need to keep a strong reference to the Target while the request is running. And you also need a different instance of Target for each picture you are going to load (because, if I am not mistaken, Picasso will cancel the previous request for a Target if a new one is started for the same Target).

EXPLANATION:

The actual reason you are having this problem is this:

Note: This method keeps a weak reference to the Target instance and will be garbage collected if you do not keep a strong reference to it. To receive callbacks when an image is loaded use into(android.widget.ImageView, Callback).

Source: http://square.github.io/picasso/2.x/picasso/com/squareup/picasso/RequestCreator.html#into-com.squareup.picasso.Target-

So, in general:

In most cases, you should use this when you are dealing with a custom View or view holder which should implement the Target interface.

BUT:

In your case I think the best solution is really to just create/find the ImageViews beforehand and have Picasso load the images directly into them.

like image 148
david.mihola Avatar answered Feb 25 '26 14:02

david.mihola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!