7

I need one help regarding cache memory in my android app. I am Running server (android) in a device. I want to do clear cache of that app programmatically. I have database in that server. Based on that database my client operations are going on. So I don't want it (Database) to get effected. I just want to clear cache not to clear data. Please help me with this.

YaMiN
  • 3,194
  • 2
  • 12
  • 36
Amith
  • 83
  • 1
  • 2
  • 10

3 Answers3

6
public class HelloWorld extends Activity {

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle *) {
      super.onCreate(*);
      setContentView(R.layout.main);
   }

   @Override
   protected void onStop(){
      super.onStop();
   }

   //Fires after the OnStop() state
   @Override
   protected void onDestroy() {
      super.onDestroy();
      try {
         trimCache(this);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void trimCache(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 {
         return false;
      }
   }
Akshay
  • 2,506
  • 4
  • 34
  • 55
Aown Raza
  • 2,023
  • 13
  • 29
6

On Kotlin you can just call

File(context.cacheDir.path).deleteRecursively()
Merthan Erdem
  • 5,598
  • 2
  • 22
  • 29
  • 1
    This one line of code works perfectly in Kotlin. – YaMiN Feb 28 '21 at 20:58
  • When I use this code, I see "Unresolved reference: context" – manjesh23 Nov 23 '21 at 15:46
  • 1
    @manjesh23 you need to get the context from somewhere (if you are outside of an activity), you need to pass it to the method. You can also try "this" instead of context or "this@YourActivity" for example – Merthan Erdem Nov 26 '21 at 19:08
3

Code for clearing the cache:

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        if (dir != null && dir.isDirectory()) {
            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();
    }
    return false;
}
luckyging3r
  • 3,047
  • 3
  • 18
  • 37
Md Hussain
  • 411
  • 4
  • 10