How to cache list data(images and names) in retrofit? Any suitable example for caching data will be more helpful?
Asked
Active
Viewed 106 times
0
-
1Possible duplicate of [Caching Images and strings using Retrofit, okhttp, picasso](https://stackoverflow.com/questions/37098999/caching-images-and-strings-using-retrofit-okhttp-picasso) – Abdul Waheed Feb 04 '19 at 11:04
-
@AbdulWaheed I have no idea about it.I m new in android development. so looking for any suitable example for this. Thanks. – TEST Feb 04 '19 at 11:16
1 Answers
0
ok. first of all you have to check headers coming in your api through postman. There you will see "Cache-Control" header. In this header, there has to be public cache value if you want to cache that api. Here is the code :
In your ApiClient.class where u kept your base URL, make this method :
public static CacheControl getCacheControl(CachePolicy cachePolicy) {
switch (cachePolicy) {
case CACHE_ONLY:
return CacheControl.FORCE_CACHE;
case NETWORK_ONLY:
return CacheControl.FORCE_NETWORK;
case NETWORK_ELSE_CACHE:
return new CacheControl.Builder().maxAge(1, TimeUnit.MINUTES).maxStale(1, TimeUnit.MINUTES).build();
case FRESH_CASHE_ELSE_NETWORK:
return new CacheControl.Builder().maxAge(1, TimeUnit.MINUTES).minFresh(1, TimeUnit.MINUTES).build();
case CACHE_ELSE_NETWORK:
return new CacheControl.Builder().immutable().build();
}
return null;
}
Now make an enum class to keep these constants :
public enum CachePolicy {
CACHE_ONLY,
NETWORK_ONLY,
NETWORK_ELSE_CACHE,
FRESH_CASHE_ELSE_NETWORK,
CACHE_ELSE_NETWORK
}
Paste this method in your ApiClient class with your base url :
public static Retrofit getClientAuthenticationWithCache(Context context, CacheControl
cacheControl) {
String URL_BASE = "your base url";
long cacheSize = 10 * 1024 * 1024; //10MiB
Cache cache = new Cache(context.getCacheDir(), cacheSize);
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder().cacheControl(cacheControl).build();
return chain.proceed(request);
}
};
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cache(cache)
.addInterceptor(interceptor)
.build();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(URL_BASE)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create());
return builder.build();
}
Now use this method in the activity/fragment where you are getting response as follow :
ApiClient.getClient(applicationContext, ApiClient.getCacheControl(CachePolicy.NETWORK_ELSE_CACHE)).create(ApiInterface::class.java)

Ashmeet Arora
- 164
- 1
- 3
- 11