How to implement my own disk cache with picasso library - Android?
Asked Answered
C

2

23

I'm using picasso library to load images for my app. But I don't how to implement my own disk (sdcard) caching with picasso library.

Coverley answered 22/9, 2013 at 14:16 Comment(4)
Will it help if I recommend alternative to Picasso that I have worked with, is easy to setup and works both in memory and on disc and is highly configurable?Gono
Picasso should already do disc caching for you. What does it not do that you need to accomplish with a custom disk cache?Meat
@Bobbake4: I just want to cache the image in custom folder in sdcard.Coverley
Picasso is using OkHttp for default and it caches. To customize cache size you can use this gist.github.com/fada21/10655652.Neomineomycin
E
36

Picasso uses the HTTP client for disk caching and if one is already configured it will use that instead of installing its own.

For the built-in UrlConnection the docs for installing a cache are here: https://developer.android.com/reference/android/net/http/HttpResponseCache.html

If you are using OkHttp then you just call setCache: http://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/OkHttpClient.html#setCache-com.squareup.okhttp.Cache-

Ehr answered 23/9, 2013 at 16:44 Comment(1)
Hi, my pics are in the Picasso cache dir but the log says: Sending progress READING_FROM_CACHE Cache content not available or expired or disabled Any idea? Thanks in advance.Moncada
M
5

@Dax, to save files in custom cache directory using OkHttp, I would code something like this -

OkHttpClient okHttpClient = new OkHttpClient();
File customCacheDirectory = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/MyCache");
okHttpClient.setCache(new Cache(customCacheDirectory, Integer.MAX_VALUE));
OkHttpDownloader okHttpDownloader = new OkHttpDownloader(okHttpClient);
Picasso picasso = new Picasso.Builder(mainActivity).downloader(okHttpDownloader).build();
picasso.load(imageURL).into(viewHolder.image);

Hope this helps.

Mccalla answered 22/10, 2015 at 8:1 Comment(2)
seCache is not recognized ?Condenser
@Condenser you're right, setCache() is no more supported. That snippet was from 2.x version, but in 3.x they've replaced the setters with builder pattern (See github.com/square/okhttp/blob/master/CHANGELOG.md). So in 3.x you can do something like OkHttpClient.newBuilder().cache(cache)...Mccalla

© 2022 - 2024 — McMap. All rights reserved.