简体   繁体   中英

How to store cache data?

In my android app I am trying to store the data browsed form my database to the phone locally in form of cache data(some data of full database that can be shown during offline mode or when phone is note connected to internet).I have no idea how to do this.Please add links of tutorials if possible.
Thank you!

Update-1

API call will generally get a JSON response and same can be cached automatically using the code provided below.It does not matter what kind of response you have.The below code is just rewriting the response header so that it will fetch the information automatically from cache even if the phone is not connected to the internet


Update-2

You can check out this url


If your are making API call you can cache the response using the Okayhttp Interceptor. You may not even need to store the data in the database, your entire response can be cached in the cache directory.You can add this interceptor if you are using the OkHttp client.

private static Cache provideCache() {
    Cache cache = null;
    try {
        cache = new Cache(new File(context.getCacheDir(), "http-cache"),
                10 * 1024 * 1024); // 10 MB
    } catch (Exception e) {
    }
    return cache;
}

public static Interceptor provideCacheInterceptor() {
    return new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());

            // re-write response header to force use of cache
            CacheControl cacheControl = new CacheControl.Builder()
                    .maxAge(60, TimeUnit.MINUTES)
                    .build();

            return response.newBuilder()
                    .header(CACHE_CONTROL, cacheControl.toString())
                    .build();
        }
    };
}

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

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

                request = request.newBuilder()
                        .cacheControl(cacheControl)
                        .build();
            }

            return chain.proceed(request);
        }
    };
}


OkHttpClient okHttpClient=new OkHttpClient.Builder()
            .addInterceptor(provideOfflineCacheInterceptor())
            .addNetworkInterceptor(provideCacheInterceptor())
            .cache(provideCache())
            .build()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM