1

I tried this link and this link to construct an offline Retrofit cache.

The problem is that if I put the phone in Airplane mode, the Response.body() is always null.

Here's my code:

OkHttpClient client = new OkHttpClient
  .Builder()
  .cache(new Cache(App.sApp.getCacheDir(), 10 * 1024 * 1024)) // 10 MB
  .addInterceptor(new Interceptor() {
    @Override public Response intercept(Chain chain) throws IOException {
      Request request = chain.request();
      if (App.isNetworkAvailable()) {
        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 = new retrofit2.Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(okHttpClient)
                    .build();

 final RetrofitServiceInterface service = RetrofitClient.getRetrofitInstance(this).create(RetrofitServiceInterface.class);
        Call<List<RetroPhoto>> call = service.getAllPhotos();
        call.enqueue(new Callback<List<RetroPhoto>>() {
            @Override
            public void onResponse(Call<List<RetroPhoto>> call, Response<List<RetroPhoto>> response) {

                generateDataList(response.body()); ////HERE!!!!
            }

            @Override
            public void onFailure(Call<List<RetroPhoto>> call, Throwable t) {
                Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
            }
        });
Mena
  • 3,019
  • 1
  • 25
  • 54

1 Answers1

0

try this code

        int cacheSize = 10 * 1024 * 1024; // 10 MB

        Cache cache = new Cache(new File(getApplication().getCacheDir(),"someIdentifier"), cacheSize);

        Interceptor offlineCacheInterceptor = new Interceptor() {
            @Override
            public Response intercept (Chain chain) throws IOException {
                Request request = chain.request();

                if(!App.isNetworkAvailable()) {
                    CacheControl cacheControl = new CacheControl.Builder()
                            .maxStale(30, TimeUnit.DAYS)
                            .build();

                    request = request.newBuilder()
                            .cacheControl(cacheControl)
                            .build();
                }
                return chain.proceed( request );
            }
        };
  • When in Airplane mode: This gets me E/error: Unable to resolve host "jsonplaceholder.typicode.com": No address associated with hostname – Mena Oct 18 '18 at 14:46
  • maybe your response has a "Pragma: no-cache" header. remove this with response interceptor this is explained in this link https://stackoverflow.com/a/47944917/8873209 –  Oct 18 '18 at 14:59
  • @Mena You have to use both addInterceptor() and addNetworkInterceptor() methods when building OkHttpKCient object. https://stackoverflow.com/questions/48187827/okhttp-3-response-cache-java-net-unknownhostexception/48208801#48208801 – Anton Prokopov Oct 22 '18 at 06:46
  • @AntonProkopov I checked your answer, This one: https://stackoverflow.com/questions/48187827/okhttp-3-response-cache-java-net-unknownhostexception/48208801#48208801 but it uses only a networkInterceptor. – Mena Oct 22 '18 at 07:46
  • @AntonProkopov Can you check this code using both interceptors and see what I am missing? https://stackoverflow.com/questions/52916443/retrofit-okhttp-offline-caching-not-working – Mena Oct 22 '18 at 07:48