为离线使用改进缓存数据

时间:2017-03-31 05:37:02

标签: android android-recyclerview retrofit

我正在使用Retrofit库来解析并将JSON数据填充到RecyclerView中。

但是,现在我想知道,我如何为离线使用存储相同的数据,(甚至互联网也不可用)。

@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);
        }
    }

应用级别: 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'
}

2 个答案:

答案 0 :(得分:11)

让我们首先使用

构建一个OKHTTP客户端

缓存 检查连接的拦截器,如果没有请求缓存数据: 这是客户。

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

我们首先创建10 MB的缓存对象,从静态应用程序上下文中获取缓存目录。

然后Interceptor在我的Application类中使用实用程序方法来检查连接性。如果有连接,我们告诉请求它可以重复使用数据60秒。

如果没有连接,我们要求在7天前仅给出(仅限缓存)“陈旧”数据。

现在让这个OkHTTP客户端成为Retrofit2的客户端,当应用程序离线时,您将能够使用旧的缓存数据

答案 1 :(得分:-4)

您可以使用GSON将您的pojo转换为String并将其保存在共享首选项中

SharedPreferences.Editor prefsEditor = PreferenceManager.getDefaultSharedPreferences(contexts;
        Gson gson = new Gson();
        String json = gson.toJson(jokesModel);
        prefsEditor.putString("save_key", json);
        prefsEditor.commit();
相关问题