Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if an image is fully loaded with Picasso

Picasso is asynchronous, so i was wondering if there is any way i can test if an image is fully loaded, before executing any additional code?

Picasso.with(context).load(imageURI).into(ImageView);
// image fully loaded? do something else ..
like image 471
Ossama Zaid Avatar asked Sep 09 '14 15:09

Ossama Zaid


2 Answers

If the image is fully loaded it will be set on the ImageView synchronously.

You can use the callback to assert this.

final AtomicBoolean loaded = new AtomicBoolean();
Picasso.with(context).load(imageURI).into(imageView, new Callback.EmptyCallback() {
  @Override public void onSuccess() {
    loaded.set(true);
  }
});
if (loaded.get()) {
  // The image was immediately available.
}
like image 54
Jake Wharton Avatar answered Nov 16 '22 01:11

Jake Wharton


Using overloaded method .into(ImageView target, Callback callback) is appropriate for your case. You can use the base implementation or extend your own like Base:

Picasso.with(context).load(url).into(target, new Callback(){
            @Override
            public void onSuccess() {

            }

            @Override
            public void onError() {

            }
        });

Extended version:

package main.java.app.picasso.test;

/**
 * Created by nikola on 9/9/14.
 */
public abstract class TargetCallback implements Callback {
    private ImageView mTarget;

    public abstract void onSuccess(ImageView target);
    public abstract void onError(ImageView target);
    public TargetCallback(ImageView imageView){
        mTarget = imageView;
    }
    @Override
    public void onSuccess() {
        onSuccess(mTarget);
    }

    @Override
    public void onError() {
        onError(mTarget);
    }

}

Usage:

Picasso.with(context).load(url).into(target, new TargetCallback(target) {
            @Override
            public void onSuccess(ImageView target) {

            }

            @Override
            public void onError(ImageView target) {

            }
        });
like image 35
Nikola Despotoski Avatar answered Nov 16 '22 01:11

Nikola Despotoski