Here is my code where i am calling api and also define cache for okhttp with retrofit:
public class DemoPresenter {
DemoView vDemoView;
private Context mContext;
public DemoPresenter(Context mcontext, DemoView vDemoView) {
this.vDemoView = vDemoView;
this.mContext = mcontext;
}
public void callAllProduct() {
if (vDemoView != null) {
vDemoView.showProductProgressBar();
}
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cache(new Cache(mContext.getCacheDir(), 10 * 1024 * 1024)) // 10 MB
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (BasicUtility.isInternet(mContext)) {
request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
} else {
request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
}
return chain.proceed(request);
}
})
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("www.xyz.com/data/")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
AllApi productApiService = retrofit.create(AllApi.class);
Call<ProductData> call = productApiService.getProduct();
try {
call.enqueue(new Callback<ProductData>() {
@Override
public void onResponse(Call<ProductData> call, Response<ProductData> response) {
ArrayList<Product> alproducts = new ArrayList<>();
try {
alproducts = response.body().getProductData();
onSuccess(alproducts);
} catch (Exception e) {
}
}
@Override
public void onFailure(Call<ProductData> call, Throwable t) {
}
});
} catch (Exception e) {
}
}
private void onSuccess(ArrayList<Product> alproducts) {
if (vDemoView != null) {
vDemoView.hideProductProgressBar();
vDemoView.onProductSuccess(alproducts);
}
}
}
Now from my main activity i am calling this presenter class:
DemoPresenter mDemoPresenter = new DemoPresenter(getApplicationContext(),this);
mDemoPresenter.callAllProduct();
Now when i run this activity with Internet connectivity then it works fine but when i disconnected internet and run this activity again then it wont load data from cache .
How can i load this data from cache if there is not internet ?