In the event based Android projects like Open Event Android, we have speakers and sponsors. And these projects needs to display image of the speakers and sponsors because it affects project a lot. So instead of every time fetching image from the server it is good to store small images(thumbnails) in the cache and load images even if device is offline. It also reduces data usage.
Picasso is mostly used image loading library for Android. It automatically handles ImageView recycling and download cancellation in an adapter, complex image transformations with minimal memory use, memory and disk caching.
But one problem is Picasso caches images for only one session by default. I mean if you close the app then all by default cached image will be removed. If you are offline then Picasso will not load cached images because of it. It will make network calls every time you open the app.
In this post I explain how to manually cache images using Picasso so that images load even if the device is offline. It will make a network call only once for a particular image and will cache image in memory.
We will use okhttp3 library for OkHttpClient.
1. Add dependency
In order to use Picasso in your app add following dependencies in your app module’s build.gradle file.
2. Make static Picasso object
Make static Picasso object in the Application class so that we can use it directly from the other activity.
3. Initialize cache
Create a File object with path as app specific cache and use this object to create a Cache object.
Here it will create a Cache object with 15MB. getCacheDir() method returns the absolute path to the application specific cache directory on the filesystem.
4. Initialize Picasso with cache
Now initialize picassoWithCache object using Picass.Builder(). Set downloader for picasso by adding new OkHttp3Downloader object.
5. Use picassoWithCache object
As it is a static object you can directly use it from any activity. All the images loaded using this picassoWithCache instance will be cached in memory.
To know more how i solved this issue in Open Event Project visit this link. To learn more about Picasso features follow the links given below.
- Documentation : http://square.github.io/picasso/2.x/picasso/
- Tutorials : https://futurestud.io/tutorials/picasso-influencing-image-caching