Try offline disk cache first then go online and fetch the image

suggest change

First, add Picasso and OkHttp to the app module's build.gradle:

compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.0.2'

The class constructed below is com.squareup.picasso.OkHttpDownloader from Picasso 2.5.2, which uses OkHttp 2. picasso2-okhttp3-downloader provides OkHttp3Downloader and is not used by this snippet.

Then make a class extending Application

import android.app.Application;

import com.squareup.picasso.OkHttpDownloader;
import com.squareup.picasso.Picasso;

public class Global extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        Picasso.Builder builder = new Picasso.Builder(this);
        builder.downloader(new OkHttpDownloader(this, Integer.MAX_VALUE));
        Picasso built = builder.build();
        built.setIndicatorsEnabled(true);
        built.setLoggingEnabled(true);
        Picasso.setSingletonInstance(built);

    }
}

Picasso.setSingletonInstance throws if Picasso.with has already been called.

Add it to the manifest as follows:

<application
        android:name=".Global">

</application>

Normal Usage

Picasso.with(getActivity())
.load(imageUrl)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(imageView, new Callback() {
    @Override
    public void onSuccess() {
        //Offline Cache hit
    }

    @Override
    public void onError() {
        //Try again online if cache failed
        Picasso.with(getActivity())
                .load(imageUrl)
                .error(R.drawable.header)
                .into(imageView, new Callback() {
            @Override
            public void onSuccess() {
                 //Online download
            }

            @Override
            public void onError() {
                Log.v("Picasso","Could not fetch image");
            }
        });
    }
});

Link to original answer

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents