99

what is the correct way to clear cache in android Application programmatically. I already using following code but its not look work for me

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

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("EEEEEERRRRRRROOOOOOORRRR", "**************** 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();
}

Image from my android phone

Martyn
  • 16,432
  • 24
  • 71
  • 104
Rizwan Ahmed
  • 1,272
  • 2
  • 16
  • 27

12 Answers12

171

If you are looking for delete cache of your own application then simply delete your cache directory and its all done !

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        deleteDir(dir);
    } catch (Exception e) { e.printStackTrace();}
}

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();
    } else if(dir!= null && dir.isFile()) {
        return dir.delete();
    } else {
        return false;
    }
}
dharmendra
  • 7,835
  • 5
  • 38
  • 71
  • On that action where you want to delete your application cache. may be it can in OnDestroy or somewhere in your app to do this – dharmendra May 28 '14 at 12:08
  • 2
    this code never deletes files. When dir.isDirectory() == false it simply returns false. Since you can't delete non empty dir, this won't work. You should add an else: `if (dir != null && dir.isDirectory()) { ... }` `else if(dir.isFile()) { return dir.delete(); }` – Pierfrancesco Soffritti Oct 05 '15 at 09:12
  • @dhams does this method also clear my shared preference data as well? cause I want to retain that and clear only images in cache!!! – Saty Nov 26 '15 at 07:19
  • 3
    @Saty: no, this does not clear the shared preferences – Taifun Jun 24 '16 at 17:46
  • @Saty shared preferences stored in different directory not cache directory. Since its a risky to clear shared preference on clearing cache becouse user might stored some important data in that and that will clear only if user clear the app data. – dharmendra Jul 01 '16 at 06:01
  • 1
    They write in documentation we don't need extra permissions to do this. "Apps require no extra permissions to read or write to the returned path, since this path lives in their private storage." https://developer.android.com/reference/android/content/Context.html#getCacheDir() – YTerle Aug 06 '16 at 17:36
  • in Android N , not supports above code, throw null array, please update answer – Yogesh Rathi Oct 22 '16 at 10:07
  • why bother deleting all subfolders programmatically,I think there is a function called deleteRecursevly or something like that which deletes a folder and its content – Ahmed Rajab Mar 07 '19 at 10:31
  • Every time this method returns "false" i.e this method is not able to delete the cache or directory of cache. Please guide me why this is returning false every time. – Gyan Swaroop Awasthi Jun 01 '20 at 11:21
  • This saved me, on my app i have to open a base64 image, i convert to file in cache, but if i want to open another one it was always opening the same picture (even if i delete the last one), with this code and deleting the cache dir it works. – E. Greeff Apr 20 '23 at 11:22
106

Kotlin has an one-liner

context.cacheDir.deleteRecursively()
Fintasys
  • 1,309
  • 1
  • 9
  • 16
  • 11
    Perfect answer, this should be available in Java too as: context.getCacheDir().deleteRecursively() – JJ Du Plessis Jun 21 '19 at 06:39
  • Are you sure this doesn't break the cache directory in some way? When I ran this and then ran `File.createTempFile("download", null)` I got "java.io.IOException: open failed: ENOENT (No such file or directory)". – AndreKR Nov 06 '22 at 17:10
20

The answer from dhams is correct (after having been edited several times), but as the many edits of the code shows, it is difficult to write correct and robust code for deleting a directory (with sub-dirs) yourself. So I strongly suggest using Apache Commons IO, or some other API that does this for you:

import org.apache.commons.io.FileUtils;

...

// Delete local cache dir (ignoring any errors):
FileUtils.deleteQuietly(context.getCacheDir());

PS: Also delete the directory returned by context.getExternalCacheDir() if you use that.

To be able to use Apache Commons IO, add this to your build.gradle file, in the dependencies part:

compile 'commons-io:commons-io:2.4'
Eirik W
  • 3,086
  • 26
  • 29
  • 3
    The compile line in gradle file now will be `implementation 'commons-io:commons-io:2.5'`. I tried 2.6 first, but i've got some error, like noSuchMethodException, so please by now just use version 2.5. Latest versions here: mvnrepository.com/artifact/commons-io/commons-io – Juan Ignacio Avendaño Huergo Jun 04 '18 at 21:07
5

I think you're supposed to place clearApplicationData() before the super.OnDestroy().

Your app can't process any methods when it has been shut down.

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Dennie
  • 743
  • 2
  • 13
  • 30
  • 3
    from where do i found this method – Amarjit May 04 '17 at 13:10
  • 1
    Basic Android activity lifecycle. Best to read up on this before continuing. https://developer.android.com/guide/components/activities/activity-lifecycle.html Or do you mean clearApplicationData()? The OP wrote that himself. – Dennie May 05 '17 at 13:30
5

If you're using kotlin, then:

context.cacheDir.deleteRecursively()
Ciprian
  • 2,879
  • 3
  • 28
  • 28
4

Try this

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

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("EEEEEERRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        int i = 0;
        while (i < children.length) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
            i++;
        }
    }

    assert dir != null;
    return dir.delete();
}
2

I am not sure but I sow this code too. this cod will work faster and in my mind its simple too. just get your apps cache directory and delete all files in directory

public boolean clearCache() {
    try {

        // create an array object of File type for referencing of cache files   
        File[] files = getBaseContext().getCacheDir().listFiles();

        // use a for etch loop to delete files one by one
        for (File file : files) {

             /* you can use just [ file.delete() ] function of class File
              * or use if for being sure if file deleted
              * here if file dose not delete returns false and condition will
              * will be true and it ends operation of function by return 
              * false then we will find that all files are not delete
              */
             if (!file.delete()) {
                 return false;         // not success
             }
        }

        // if for loop completes and process not ended it returns true   
        return true;      // success of deleting files

    } catch (Exception e) {}

    // try stops deleting cache files
    return false;       // not success 
}

It gets all of cache files in File array by getBaseContext().getCacheDir().listFiles() and then deletes one by one in a loop by file.delet() method

Javid
  • 145
  • 1
  • 10
  • Code-only answers are discouraged because they do not explain how they resolve the issue. Please update your answer to explain how this improves on the other accepted and upvoted answers this question already has, and to remove the multiple instances of invalid text in the code ("enter code here"). Please review [How do I write a good answer](https://stackoverflow.com/help/how-to-answer). – FluffyKitten Sep 24 '17 at 02:23
2

If you using Android Studio 4.4.2

getCacheDir().delete();
m4n0
  • 29,823
  • 27
  • 76
  • 89
  • 2
    Does not work. From the docs: "If this pathname denotes a directory, then the directory must be empty in order to be deleted." – hej2010 Aug 14 '22 at 12:54
1

Put this code in onStop() method of MainActivity

@Override
protected void onStop() {
    super.onStop();
    AppUtils.deleteCache(getApplicationContext());
}
public class AppUtils {
    public static void deleteCache(Context context) {
        try {
            File dir = context.getCacheDir();
            deleteDir(dir);
        } catch (Exception e) {}
    }

    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();
        } else if(dir!= null && dir.isFile()) {
            return dir.delete();
        } else {
            return false;
        }
    }
}
Boken
  • 4,825
  • 10
  • 32
  • 42
Dyno Cris
  • 1,823
  • 1
  • 11
  • 20
0

Using kotlin: to just remove the content:

for (file:File in context?.cacheDir?.listFiles()!!){
             file.delete()
         }
Edwin Paz ss. -
  • 177
  • 2
  • 5
0

This code helped me:

// your code
deleteCache(getContext);
//

public void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        if (dir.list() != null) {
            deleteDir2(dir);
        }
    } catch (Exception e) { e.printStackTrace();}
}

public boolean deleteDir2(File dir) {
    if (dir.isDirectory()) {
        for (File child : dir.listFiles()) {
            boolean success = deleteDir2(child);
            if (!success) {
                return false;
            }
        }
    }
    return dir.delete();
}
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 26 '21 at 10:09
-2

This code will remove your whole cache of the application, You can check on app setting and open the app info and check the size of cache. Once you will use this code your cache size will be 0KB . So it and enjoy the clean cache.

 if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
            ((ActivityManager) context.getSystemService(ACTIVITY_SERVICE))
                    .clearApplicationUserData();
            return;
        }