Created
August 20, 2016 06:25
-
-
Save avraampiperidis/b14cd6c70fc3fed38f7cb6b93e42d020 to your computer and use it in GitHub Desktop.
Android LruCache Wrapper. easy to use between activities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.support.annotation.NonNull; | |
import android.support.v4.util.LruCache; | |
public class AppCache<T> { | |
private final int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024); | |
private final int cacheSize = maxMemory / 6; | |
private LruCache<String,T> cache; | |
private static volatile AppCache appCache; | |
private AppCache() { | |
if(cache == null) { | |
cache = new LruCache<String,T>(cacheSize); | |
} | |
} | |
public static <T> T getInstance() { | |
if(appCache == null) { | |
synchronized (AppCache.class) { | |
if(appCache == null) { | |
appCache = new AppCache(); | |
return (T)appCache; | |
} | |
} | |
} | |
return (T)appCache; | |
} | |
public LruCache<String,T> getCache() { | |
return cache; | |
} | |
public void put(@NonNull String key,T t) { | |
if(cache == null) { | |
cache = new LruCache<String,T>(cacheSize); | |
} | |
cache.put(key,t); | |
} | |
public <T> T get(@NonNull String key) { | |
if(key == null) { | |
return null; | |
} | |
if(cache == null) { | |
return null; | |
} | |
return (T)cache.get(key); | |
} | |
public <T> T remove(String key) { | |
return (T)cache.remove(key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment