Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picasso first run not call onBitmapLoaded in for loop

I have problem with get bitmap use Picasso in for loop.

it is not called onBitmapLoaded in first run.

second run it called

for (int i = 0; i < 3; i++) { 
            final int k=i;
            Picasso.with(this)
                    .load(ListA.get(i).getImage()) //image
                    .resize(100, 100)
                    .transform(new ImageTrans_CircleTransform())
                    .into(new Target() {
                        @Override
                        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {                         
                            Log.i("load", "Ok " + k);   
                           //use bitmap for add marker to map                
                        }

                        @Override
                        public void onBitmapFailed(Drawable errorDrawable) {
                        }

                        @Override
                        public void onPrepareLoad(Drawable placeHolderDrawable) {
                            Log.i("load", "first " + k);
                        }
                    });  
        }

Log

11-04 16:42:22.222  11677-11677/com.tenten I/load﹕ first___0 
11-04 16:42:22.222  11677-11677/com.tenten I/load﹕ first___1 
11-04 16:42:22.232  11677-11677/com.tenten I/load﹕ first___2 

I use picasso to get bitmap from list image.

I need bitmap not imageview.

Thank you. :D

like image 612
dungtv Avatar asked Nov 04 '15 09:11

dungtv


1 Answers

A common issue with using Picasso's Targets is that people don't keep strong references to them. This results in the targets being randomly working, because sometimes they get collected by the GC before being finished, and sometimes they live long enough to get the callback called.

What you have to do is to store those callbacks somewhere until they are finished. Here's an example:

final List<Target> targets = new ArrayList<Target>();
for (int i = 0; i < 3; i++) { 
    final int k=i;
    Target target = new Target() {

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {                         
            Log.i("Targets", "Loaded: " + k);   
            targets.remove(this);                
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
            targets.remove(this);
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
            Log.i("Targets", "Preparing: " + k);
        }
    }
    targets.add(target);
    Picasso.with(this)
        .load(ListA.get(i).getImage()) // Start loading the current target
        .resize(100, 100)
        .into(target);  
}

To make sure the list does not get GC'd too, make targets a global variable.

like image 86
Daniel Zolnai Avatar answered Oct 18 '22 13:10

Daniel Zolnai