NickUnuchek
NickUnuchek

Reputation: 12857

How to cache images with Picasso async?

At start of my application I have list of imageLinks

 List<String> imageLinks = Arrays.asList("http://example.com/1.png",
    "http://example.com/2.png",
    "http://example.com/3.png"
    ...
    "http://example.com/n.png");

I want to download the images async and in next run of my app without internet connection, I want to display the images with Picasso:

mPicasso.load("http://example.com/1.png").into(imageView)

But when I'm trying to download the image in background (io) thread with rxJava. I want to download it in background (io) thread, because I need to display ProgressDialog while images are downloading and go to another activity when it will be done

for (String imageLink:imageLinks )
    mPicasso.load(imageLink).into(new SimpleTarget()
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    Log.e(TAG, "onBitmapLoaded: "+imageLink);
                    subscriber.onNext(true);
                    subscriber.onCompleted();
                })

the error occurs:

java.lang.IllegalStateException: Method call should happen from the main thread.
    at com.squareup.picasso.Utils.checkMain(Utils.java:136)
    at com.squareup.picasso.RequestCreator.into(RequestCreator.java:496)

My another idea is to download the images with Retrofit , but how to add downloaded image to Picasso disk cache to display it in next time?

Upvotes: 0

Views: 794

Answers (3)

NickUnuchek
NickUnuchek

Reputation: 12857

Found solution Picasso.fetch(Callback)

In my case:

 mPicasso.load(imageLink).fetch(new Callback() {
                @Override
                public void onSuccess() {
                    Log.e(TAG, "onBitmapLoaded: " + imageLink);
                    subscriber.onNext(true);
                    subscriber.onCompleted();
                }

                @Override
                public void onError() {
                    Log.e(TAG, "onBitmapFailed: " + imageLink);
                    subscriber.onNext(false);
                    subscriber.onCompleted();
                }
            });

Upvotes: 0

Android developer
Android developer

Reputation: 1322

Just like the message from the exception you posted says - you need to make your Picasso request on the main thread.

Don't be afraid it won't do the actual image (down)loading on the thread you made a call from. This is exactly why loading into Picasso's Targets is described as an "asynchronous" way of loading images. You used the word "async" in your very question but I'm afraid you don't fully understand yet what this means.

Upvotes: 0

Clapa Lucian
Clapa Lucian

Reputation: 600

I suppose you could use this

Bitmap bitmap = Picasso.with(this)
                        .load(productCoverImageURL)
                        .get();

Use that inside your RxJava async job

Upvotes: 1

Related Questions