Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit Cache Data for Offline Usage

I am using Retrofit library to parse and populate JSON data into RecyclerView.

But, Now I would like to know, How could I store same data for Offline usage, (even Internet is not available).

@Override
    public void onResume() {
        super.onResume();
        subscription = sampleAPI.getSamples()
                .cache()
                .timeout(5000, TimeUnit.MILLISECONDS)
                .retry(1)
                .doOnUnsubscribe(new Action0() {
                    @Override
                    public void call() {
                        Log.d(getClass().getName(), "Called unsubscribe OnPause()");
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<SampleTypePojo>() {
                               @Override
                               public void call(SampleTypePojo jokesModel) {
                                   sampleList = jokesModel.getValue();

                                   displaySampleList(sampleList);

                               }
                           }, new Action1<Throwable>() {
                               @Override
                               public void call(Throwable throwable) {
                                   Log.e(getClass().getName(), "ERROR: " + throwable.getMessage());
                                   throwable.printStackTrace();

                               }
                           }
                );
    }

    private void getSampleData() {
        if (sampleAPI == null) {
            sampleAPI = new RestAdapter.Builder()
                    .setEndpoint(Constants.BASE_URL)
                    .setLogLevel(RestAdapter.LogLevel.FULL)
                    .build()
                    .create(SampleAPI.class);
        }
    }

app level: build.gradle

dependencies {
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'io.reactivex:rxjava:1.0.4'
    compile 'io.reactivex:rxandroid:0.24.0'
}
like image 524
Sophie Avatar asked Dec 11 '22 12:12

Sophie


1 Answers

Let’s first build a OKHTTP client with

a cache an interceptor that checks for connectivity and if none asks for cached data: Here’s the client.

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();

We first create the cache object with 10 MB, getting the cache directory from a static Application context.

Then the Interceptor uses a utility method in my Application class to check for connectivity. If there is connectivity, we tell the request it can reuse the data for sixty seconds.

If there’s no connectivity, we ask to be given only (only-if-cached) ‘stale’ data upto 7 days ago.

Now make this OkHTTP client your client for Retrofit2 and you will be able to use your old cached data when the app goes offline

like image 66
Christoph Mayr Avatar answered Jan 10 '23 06:01

Christoph Mayr