Reputation: 2829
I am beginner to android. I want to use Memory Cache in my application to store images in memory cache and clear it when those images are not required to be in cache! Any help will be greatly appreciated.
Upvotes: 1
Views: 7943
Reputation: 1084
Memory caching is a function of java, not Android.
import java.util.*
Then use List, Map, ArrayList and HashMap to build a name/value paired array of memory mapped objects and store it as a hashmap. You can then access (read/delete/update) objects in memory via the hashmap.
If you need to save the memory objects for future instantiations (e.g. through application stop and start), only then do you need to write the data to external storage (presumably, images and all), and read it again, as needed.
However, in most cases, you are building the local memory cache because you have just retrieved the data and would like other classes to process it now or in the near future. If your application cannot find data because it restarted, or it is no longer in memory because of memory constraints, it's best to retrieve the data again and not rely on potentially stale cache files.
Upvotes: 0
Reputation: 4638
Please use the following code and let me know .
public class MyApplication extends Application {
private static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static MyApplication getInstance() {
return instance;
}
public void clearApplicationData() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));
Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
}
}
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
}
Upvotes: 0
Reputation: 1001
You can use WeakHashMap to implement a simple caching method. It's elements will be garbage collected, so if your application uses up its heap, then it will be freed, but until that you can have the images in the memory.
Upvotes: 2