I'm using the following code to load an URL to an ImageView. It first tries to load from cache, and if it fails it tries to fetch it from internet:
Picasso.with(getActivity())
.load(imageUrl)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(imageView, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
//Try again online if cache failed
Picasso.with(getActivity())
.load(imageUrl)
.error(R.drawable.error_image)
.into(imageView, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Log.v("Picasso","Could not fetch image");
}
});
}
});
It works just fine, but the problem is that is really cumbersome to write all this code every time I have to load an image, compared to the standard:
Picasso.with(getContext())
.load(imageUrl)
.into(imageView);
Is there a way to encapsulate this behaviour ? Does Picasso provide any way to help it?
@ianhanniballake comment was right, and this SO answer is misleading. To enable caching, you only have to add to your Application:
Picasso.Builder builder = new Picasso.Builder(this);
builder.downloader(new OkHttpDownloader(this, Integer.MAX_VALUE));
Picasso.setSingletonInstance(builder.build());
And then Picasso/OkHttp takes care of looking in the cache before it tries to load an image from internet.