Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Clear Application Cache Programatically.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 166
    Comment on it

    Clear Cache Programatically

    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();
    }

     

    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
        }
    }

    Here is a full working demo for the above tutorial click here to view.

     

    Happy Coding :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: