Skip to content

Instantly share code, notes, and snippets.

@lalbuquerque
Last active March 13, 2016 22:46
Show Gist options
  • Save lalbuquerque/83aac32d90c8e9ceac90 to your computer and use it in GitHub Desktop.
Save lalbuquerque/83aac32d90c8e9ceac90 to your computer and use it in GitHub Desktop.
An util class for cleaning app data before running an Android automated test
public class AppDataCleaner {
public static void clearApplicationData(Context context) {
File cache = new File(context.getFilesDir().getAbsolutePath());
File appDir = new File(cache.getParent());
if (appDir != null && appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (s.equals("shared_prefs")) {
clearSharedPreferences(new File(appDir, s), context);
} else if (!s.equals("lib")) {
deleteDir(new File(appDir, s));
Log.i("AppDataCleaner", "**************** File " + appDir + " " + s + " REMOVED *******************");
}
}
}
}
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]));
Log.i("AppDataCleaner", "REMOVING: " + children[i]);
if (!success) {
return false;
}
}
}
return dir.delete();
}
private static void clearSharedPreferences(File dir, Context context) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
String sharedFile = children[i];
Log.i("AppDataCleaner", "Shared Prefs removed: " + sharedFile.split("[.]")[0]);
context.getSharedPreferences(sharedFile.split("[.]")[0], Context.MODE_PRIVATE).edit().clear().commit();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment