over 8 years ago
Hello All,
This is a simple tutorial to clear cache of your application, Sometimes there is need in our application to store some of the files on device cache and we don have the choice to move them to SD cards as they are required at run time and we can not take the risk of loosing them due to memory card removal. In such cases a problem may arise "low memory" because you already have eaten up enough memory, So here is a simple solution.
Step :1
Put your code that stores data in cache into a try catch (life saver) block, and put a check on exception if it has raised due to low memory make space for some new data by erasing the cache of app.
Step 2:
Delete the cache using following code.
- /**
- * deletes the files of the cache.
- * @param dir
- * @return
- */
- 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;
- }
- }
- }
- // The directory is now empty so delete it
- return dir.delete();
- }
/** * deletes the files of the cache. * @param dir * @return */ 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; } } } // The directory is now empty so delete it return dir.delete(); }
The parameter above requires is the file that need to be deleted which comes from the following method.
- /**
- * checks is if file exits and calls for deletion
- * @param context
- */
- public static void trimCache(Context context) {
- try {
- File dir = context.getCacheDir();
- if (dir != null && dir.isDirectory()) {
- deleteDir(dir);
- }
- } catch (Exception e) {
- // TODO: handle exception
- }
- }
/** * checks is if file exits and calls for deletion * @param context */ public static void trimCache(Context context) { try { File dir = context.getCacheDir(); if (dir != null && dir.isDirectory()) { deleteDir(dir); } } catch (Exception e) { // TODO: handle exception } }
Here is a full working demo for the above tutorial click here to view.
Happy Coding :)
Can you help out the community by solving one of the following Version Control problems?
Do activity (Answer, Blog) > Earn Rep Points > Improve Rank > Get more opportunities to work and get paid!
For more topics, questions and answers, please visit the Tech Q&A page.
0 Comment(s)