Skip to content

Instantly share code, notes, and snippets.

@elliottsj
Created January 3, 2014 21:00
Show Gist options
  • Save elliottsj/8246499 to your computer and use it in GitHub Desktop.
Save elliottsj/8246499 to your computer and use it in GitHub Desktop.
import com.jakewharton.disklrucache.DiskLruCache;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class MyCache {
DiskLruCache mDiskLruCache;
public MyCache(File directory) throws IOException {
mDiskLruCache = DiskLruCache.open(directory, 1, 1, 20 * 2^20);
}
public void put(String key, Object object) {
DiskLruCache.Editor editor = null;
try {
editor = mDiskLruCache.edit(key);
if (editor == null) {
return;
}
ObjectOutputStream out = new ObjectOutputStream(editor.newOutputStream(0));
out.writeObject(object);
out.close();
editor.commit();
} catch (IOException e) {
e.printStackTrace();
}
}
public Object get(String key) {
DiskLruCache.Snapshot snapshot;
try {
snapshot = mDiskLruCache.get(key);
ObjectInputStream in = new ObjectInputStream(snapshot.getInputStream(0));
return in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return null;
}
}
import android.content.Context;
import android.test.AndroidTestCase;
import android.test.IsolatedContext;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MyCacheTest extends AndroidTestCase {
File mDirectory;
MyCache myCache;
public void setUp() throws Exception {
Context context = getContext();
IsolatedContext isolatedContext = new IsolatedContext(context.getContentResolver(), context);
mDirectory = isolatedContext.getCacheDir();
myCache = new MyCache(mDirectory);
}
public void tearDown() throws Exception {
myCache.mDiskLruCache.delete();
myCache.mDiskLruCache.close();
}
public void testPutGet() throws Exception {
List<String> list = new ArrayList<String>();
list.add("first string");
list.add("second string");
myCache.put("test-array-list", list);
// Close and re-open the cache, forcing it to read from disk
myCache.mDiskLruCache.close();
myCache = new MyCache(mDirectory);
List<String> actual = (List<String>) myCache.get("test-array-list");
assertNotNull(actual); // test fails here
assertEquals(list, actual);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment