Skip to content

Instantly share code, notes, and snippets.

@konmik
Created December 25, 2014 19:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save konmik/54c862feb512fc4fe01d to your computer and use it in GitHub Desktop.
Save konmik/54c862feb512fc4fe01d to your computer and use it in GitHub Desktop.
StringDiskLruCache based on Jake Warthon's DiskLruCache
public class StringDiskLruCache {
private static final int EXPIRATION = 1000 * 60 * 60 * 24;
private static final int DATA_INDEX = 0;
private static final int EXPIRATION_INDEX = 1;
private static final int INDEXES_COUNT = 2;
private Context context;
private DiskLruCache cache;
@Inject
public StringDiskLruCache(App app) {
this.context = app;
open(context);
}
private void open(Context context) {
try {
File dir = new File(context.getCacheDir(), getClass().getSimpleName());
int versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
cache = DiskLruCache.open(dir, versionCode, INDEXES_COUNT, 3 * 1024 * 1024);
}
catch (Exception e) {
printException(e);
}
}
public void remove(String key) {
try {
cache.remove(key);
}
catch (IOException e) {
e.printStackTrace();
}
}
public void put(String key, String value) {
try {
DiskLruCache.Editor editor = cache.edit(key);
editor.set(DATA_INDEX, value);
editor.set(EXPIRATION_INDEX, "" + (System.currentTimeMillis() + EXPIRATION));
editor.commit();
}
catch (Exception e) {
e.printStackTrace();
}
}
public String get(String key) {
try {
DiskLruCache.Snapshot entry = cache.get(key);
if (entry != null)
return entry.getString(DATA_INDEX);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public boolean isValid(String key) {
try {
DiskLruCache.Snapshot entry = cache.get(key);
return entry != null && Long.parseLong(entry.getString(EXPIRATION_INDEX)) < System.currentTimeMillis();
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
public void invalidate() {
try {
cache.delete();
}
catch (IOException e) {
e.printStackTrace();
}
open(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment