A simple Android utils library to write any type of data into cache files and read them later.

Overview

CacheUtilsLibrary

Android Arsenal Maven Central Android Gems

This is a simple Android utils library to write any type of data into cache files and then read them later, using Gson to serialize and deserialize these data.

中文版请看这里

##Gradle

compile 'com.lifeofcoding:cacheutilslibrary:1.1.0@aar'
compile 'com.google.code.gson:gson:2.2.2'
compile 'commons-io:commons-io:2.4'

If you have errors like:

duplication file during packaging of APK ...
Path in archive: META-INF/LICENSE.txt
...

Please add such code in your android entry of your build.gradle file:

packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/ASL2.0'
    exclude 'META-INF/MANIFEST.MF'
}

##Configuration You need to configure CacheUtilsLibrary in your Application class.

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        // configure CacheUtilsLibrary
        CacheUtils.configureCache(this);
    }
}

Don't forget to declare the MyApplication class in your AndroidManifest.xml file.

##Usage All sample code can be found in the MainActivity file. #####Cache String File

// write
CacheUtils.writeFile(CACHE_FILE_STRING, CACHE_FILE_CONTENT_STRING);

// read
String fileContent = CacheUtils.readFile(CACHE_FILE_STRING);

#####Cache Map<String, T> File

// write
CacheUtils.writeDataMapFile(CACHE_FILE_MAP, getCacheFileContentMap());

// read
Map<String, Object> mapData = CacheUtils.readDataMapFile(CACHE_FILE_MAP);

// get mapData
private static Map<String, Object> getCacheFileContentMap() {
    Map<String, Object> mapData = new HashMap<>();
    mapData.put("firstItem", "item0");
    mapData.put("secondItem", 1);
    mapData.put("thirdItem", false);
    return mapData;
}

#####Cache List<Map<String, T> File

// write
CacheUtils.writeDataMapsFile(CACHE_FILE_LIST_MAP, getCacheFileContentListMap());

// read
List<Map<String, Object>> listMapData = CacheUtils.readDataMapsFile(CACHE_FILE_LIST_MAP);

// get listMapData
private static List<Map<String, Object>> getCacheFileContentListMap() {
    List<Map<String, Object>> listMapData = new ArrayList<Map<String, Object>>();

    for (int i = 0; i < 4; i++) {
        Map<String, Object> item = new HashMap<>();
        item.put("firstItemAt" + i, "item0At" + i);
        item.put("secondItemAt" + i, 1 + i);
        item.put("thirdItemAt" + i, i % 2 == 0);
        listMapData.add(item);
    }
    return listMapData;
}

#####Cache Object File

// write
CacheUtils.writeObjectFile(CACHE_FILE_OBJECT, MyClass.SAMPLE_MYCLASS_1);

// read
MyClass myClassSample = CacheUtils.readObjectFile(CACHE_FILE_OBJECT, new TypeToken<MyClass>(){}.getType());

You can see MyClass and MyClass.SAMPLE_MYCLASS_1 here and here.

#####Cache List<Object> File

// write
CacheUtils.writeObjectFile(CACHE_FILE_LIST_OBJECT, getCacheFileContentListObject());

// read
List<MyClass> myClassList = CacheUtils.readObjectFile(CACHE_FILE_LIST_OBJECT, new TypeToken<List<MyClass>>(){}.getType());

// get List<MyClass> data
private static List<MyClass> getCacheFileContentListObject() {
    List<MyClass> listObject = new ArrayList<>();
    listObject.add(MyClass.SAMPLE_MYCLASS_1);
    listObject.add(MyClass.SAMPLE_MYCLASS_2);
    listObject.add(MyClass.SAMPLE_MYCLASS_3);
    return listObject;
}

##License

Copyright 2015-2016 Wesley Lin

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
You might also like...
Screen Capture Utils - A plugin to handle screen capture events on android and ios

Screen Capture Utils A plugin to handle screen capture events on android and ios 🚀 Initialize SDK late ScreenCaptureUtils screenCaptureUtils;

A utils to change statusbar for Android.
A utils to change statusbar for Android.

StatusBar 一个Android状态栏工具类,可以设置状态栏颜色、文字深浅、是否隐藏状态栏。 效果预览 注意 最低支持版本为Android5.0(minSdkVersion 21) 本项目仅提供AndroidX版本 在setContentView()之后调用 特点 支持状态栏颜色修改 支持状态

The most comprehensive utils of ViewBinding.

ViewBinding reduces exceptions caused by id or type errors, which are recommended by both Google officials and Jake Wharton, but it can be a bit cumbersome to use, so this library can help you use ViewBinding with as little code as possible in any usage scenario.

Java implementation of a Disk-based LRU cache which specifically targets Android compatibility.

Disk LRU Cache A cache that uses a bounded amount of space on a filesystem. Each cache entry has a string key and a fixed number of values. Each key m

CreditCardHelper 🖊️  A Jetpack-Compose library providing useful credit card utilities such as card type recognition and TextField ViewTransformations
CreditCardHelper 🖊️ A Jetpack-Compose library providing useful credit card utilities such as card type recognition and TextField ViewTransformations

CreditCardHelper 🖊️ A Jetpack-Compose library providing useful credit card utilities such as card type recognition and TextField ViewTransformations

Utility library that utilizes KSP to generate Room type converter classes.

Roomie Roomie is an annotation processing library that utilizes KSP to geaRoomie is an annotation processing library that utilizes KSP to generate TypeConverter classes for Room. TypeConverter classes most often involve same boiler-plate code and Roomie makes it really easy to quickly create them with a single annotation.nerate TypeConverter classes for Room. TypeConverter classes most often invol

Type safe intent building for services and activities

#IntentBuilder Type safe intent building for services and activities. IntentBuilder is a type safe way of creating intents and populating them with ex

SharedPreference Library to save all types including your custom types and observe them if need be.

A SharedPreference Library that can be used to store all types including your custom classes and observe them too if needed.

Validator - Notify type based validation for input fields.
Validator - Notify type based validation for input fields.

Validator - Notify type based validation for input fields.

Comments
  • Data already written is cleared from cache with new write request

    Data already written is cleared from cache with new write request

    In the sample code, since we are saving the data in utf-8 format to a cache file in the device storage, every time a new write request is made, the existing written data is flushed out.

    To solve this I appended the content of the file using the FileOutputStream(String path, boolean append) constructor like this : IOUtils.write(fileContent, new FileOutputStream(pathForCacheEntry(fileName),true), ENCODING);

    But with this approach the buildGson from JSON for MyClass and Map<String> data types do not work as the data is not in valid JSON format.

    opened by Ruchita7 1
  • Error when reading from cached HashMap

    Error when reading from cached HashMap

    I'm getting a com.google.gson.internal.LinkedTreeMap cannot be cast to <CustomClass> error when reading a HashMap from cache.

    Writing to file:

    Map<String, Bus> buses = new HashMap<>();
    //after adding data
    CacheUtils.writeDataMapFile(CACHE_NAME, buses);
    

    Reading from file:

    buses = CacheUtils.readDataMapFile(CACHE_NAME);
    Bus b = buses.get("Route 1"); //Error here
    
    opened by jaytj95 1
Android binary resources read/write library

Android binary resources read/write library

REAndroid 23 Jan 4, 2023
MMDUtils is a library for read/write mmd related file in java

MMDUtils MMDUtils is a library for read/write mmd related file in java Features Read/Write VMD(Vocaloid Motion Data) file Read/Write PMX(Polygon Model

null 5 Jan 28, 2022
A low intrusive, configurable android library that converts layout XML files into Java code to improve performance

qxml English 一个低侵入,可配置的 Android 库,用于将 layout xml 文件转换为 Java 代码以提高性能。 与X2C的对比 X2C: 使用注解处理器生成View类,使用时需要在类中添加注解,并替换setContentView方法,侵入性较强; 对于布局属性的支持不够完美

null 74 Oct 6, 2022
DiskCache - Simple and readable disk cache for kotlin and android applications

DiskCache Simple and readable disk cache for kotlin and android applications (with journaled lru strategy) This is a simple lru disk cache, based on t

Giovanni Corte 14 Dec 2, 2022
a simple cache for android and java

ASimpleCache ASimpleCache 是一个为android制定的 轻量级的 开源缓存框架。轻量到只有一个java文件(由十几个类精简而来)。 1、它可以缓存什么东西? 普通的字符串、JsonObject、JsonArray、Bitmap、Drawable、序列化的java对象,和 b

Michael Yang 3.7k Dec 14, 2022
Multiplaform kotlin library for calculating text differences. Based on java-diff-utils, supports JVM, JS and native targets.

kotlin-multiplatform-diff This is a port of java-diff-utils to kotlin with multiplatform support. All credit for the implementation goes to original a

Peter Trifanov 51 Jan 3, 2023
Expirable Disk Lru Cache is a secure(with encryption) wrapper for [DiskLruCache](https://github.com/JakeWharton/DiskLruCache) that allows expiring of key/value pairs by specifying evictionTimeSpan. It has very simple API.

ExpirableDiskLruCache ExpirableDiskLruCache is a wrapper for DiskLruCache that allows expiring of key/value pairs by specifying evictionTimeSpan. It h

Vijay Rawat 24 Oct 3, 2022
🇧🇷 Utils library for Brazilian specific businesses

???? Brazilian Toolkit ???? Utils library for Brazilian specific businesses. Including in your project Gradle Add below codes to your root build.gradl

Geovani Amaral 14 Jan 7, 2023
🇧🇷 Utils library for Brazilian specific businesses

???? Brazilian Toolkit ???? Utils library for Brazilian specific businesses. Including in your project Gradle Add below codes to your root build.gradl

Geovani Amaral 13 Aug 13, 2022
Android library to easily serialize and cache your objects to disk using key/value pairs.

Deprecated This project is no longer maintained. No new issues or pull requests will be accepted. You can still use the source or fork the project to

Anup Cowkur 667 Dec 22, 2022