27

I am allowing the user to create multiple SharedPreferences files, but I also would like the option for them to delete these files. I know I could use internal storage, but that is not my question.

My question is: "How can I delete in code or manually (not just clear) a SharedPreferences file?"

Community
  • 1
  • 1
Andrew
  • 830
  • 3
  • 10
  • 27
  • 2
    Did you try the clear() method. I think it is actually meant for removing all the values stored in the shared preference. So once you provide that your users will be provided with the default value of the shared preference. – Andro Selva May 25 '11 at 13:38
  • 1
    `clear()` will clear out the file, but will not delete the file from the file system. A poorly designed app (like mine) could end up with many many empty files, taking up space. @kirill's & @inazaruk's method seems to work for me. – Richard Le Mesurier Jul 16 '13 at 21:17

5 Answers5

36

If you get SharedPreferences instance via Context.getSharedPreferences("X"), then your file will be named X.xml.

It will be located at /data/data/com.your.package.name/shared_prefs/X.xml. You can just delete that file from the location. Also check /data/data/com.your.package.name/shared_prefs/X.bak file, and if it exists, delete it too.

But be aware, that SharedPreferences instance saves all data in memory. So you'll need to clear preferences first, commit changes and only then delete preferences backing file.

This should be enough to implement your design decision.

inazaruk
  • 74,247
  • 24
  • 188
  • 156
  • Oh, so even if I just deleted the file without clearing it first the data would still be taking up memory? Also, could you point me towards a tutorial or something that shows how to go into a directory and delete a file. thanks – Andrew May 25 '11 at 13:52
  • 5
    Yes, it might keep data in memory for some time. It may detect that file was deleted and clear itself, but I wouldn't recommend to rely on that. As for deleting files see documentation: http://developer.android.com/reference/java/io/File.html#File%28java.lang.String%29. Its quite easy: `File file= new File("/data/data/.../shared_prefs/X.xml");` and then `file.delete();` – inazaruk May 25 '11 at 13:56
  • You can delete programmatically the shared preferences file on non-routed devices? – Paul Sep 27 '12 at 14:00
  • 6
    The answer to my above question is: NO. – Paul Sep 28 '12 at 12:56
  • @Paul Deleting programmatically seems to work for me (Nexus 7, not rooted, signed app). But have not checked with app submitted to store yet... – Richard Le Mesurier Jul 16 '13 at 21:15
  • You should be able to delete preference files. All preference files are created with UID of your application as owner. So your application has all required permissions. – inazaruk Jul 17 '13 at 18:20
  • 2
    Instead of hard-coding the path, you can use `context.getFilesDir().getParent() + File.separator + "shared_prefs"` (the files directory is a sibling of the shared_prefs directory). – arlomedia Aug 02 '14 at 00:39
  • Doesn't seem to work for me. Or rather, the file deletion apparently goes fine... I get a positive outcome from `file.delete()`... but then when I check the content of the shared prefs folder after that, the file is still there :-/ – drmrbrewer Jun 24 '20 at 10:35
  • If delete == true, file still exist – ilw Jan 05 '21 at 17:35
32

Here is an easy method to clear all the SharedPreferences for a given context, usefull for unit-tests

public static void clearSharedPreferences(Context ctx){
    File dir = new File(ctx.getFilesDir().getParent() + "/shared_prefs/");
    String[] children = dir.list();
    for (int i = 0; i < children.length; i++) {
        // clear each preference file
        ctx.getSharedPreferences(children[i].replace(".xml", ""), Context.MODE_PRIVATE).edit().clear().commit();
        //delete the file
        new File(dir, children[i]).delete();
    }
}

Note that when you are using this for Android Unit testing and you are using sharedpreferences in your Application class, this might cause a race condition and it might not work properly.

KraffMann
  • 322
  • 1
  • 4
  • 14
Kirill Kulakov
  • 10,035
  • 9
  • 50
  • 67
  • 3
    Best answer that i found so far – Marco May 23 '16 at 17:23
  • Can't rely on hard coded paths. Who knows what Google may change in the next android version. :( – Mohit Atray Oct 17 '21 at 18:27
  • Thank you so so much. I was stuck on an AEADBadTagException after using EncryptedSharedPreferences and deleting my app and re-installing it. This was an easy solution that completely solved it for me! – jhwblender Dec 22 '22 at 23:58
9
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    context.deleteSharedPreferences(preferencesKey);
} else {
    try {
        org.apache.commons.io.FileUtils.cleanDirectory(new File(context.getCacheDir().getParent() + "/shared_prefs/"));
    } catch (IOException e) {
        Log.e(TAG, "Cannot delete files in shared pref directory", e);
    }
}
azizbekian
  • 60,783
  • 13
  • 169
  • 249
ABS
  • 1,101
  • 10
  • 27
9

Java:

public static boolean deleteSharedPreferences(Context context, String name) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return context.deleteSharedPreferences(name);
    } else {
        context.getSharedPreferences(name, MODE_PRIVATE).edit().clear().apply();
        File dir = new File(context.getApplicationInfo().dataDir, "shared_prefs");
        return new File(dir, name + ".xml").delete();
    }
}

Kotlin:

companion object {
    fun deleteSharedPreferences(context: Context, name: String): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return context.deleteSharedPreferences(name)
        } else {
            context.getSharedPreferences(name, MODE_PRIVATE).edit().clear().apply()
            val dir = File(context.applicationInfo.dataDir, "shared_prefs")
            return File(dir, "$name.xml").delete()
        }
    }
}
ElegyD
  • 4,393
  • 3
  • 21
  • 37
4

Its simple Genius!

Your default sd card preference.xml file path might be: /data/data/your package name/shared_prefs/your shared preference xml file.

like, /data/data/com.hirecraft.hirecraftmanager/shared_prefs/swipe_preferences.xml.

delete preference xml file:

File deletePrefFile = new File("/data/data/com.hirecraft.hirecraftmanager/shared_prefs/swipe_preferences.xml");
deletePrefFile.delete();

Or get file path in String like,

String filePath = getApplicationContext().getFilesDir().getParent()+"/shared_prefs/swipe_preferences.xml";
File deletePrefFile = new File(filePath );
 deletePrefFile.delete();
user3425867
  • 644
  • 6
  • 14
Silambarasan Poonguti
  • 9,386
  • 4
  • 45
  • 38
  • The 2nd option is wrong. getApplicationContext().getFilesDir().getPath()+"/"+"shared_prefs/ leads to /data/data/com.hirecraft.hirecraftmanager/files/shared_prefs/swipe_preferences.xml !!! The shared_prefs folder is not under files folder. Downvote for the 2nd option. – goseib Mar 22 '15 at 19:05
  • 1
    The 2nd option is wrong. getApplicationContext().getFilesDir().getPath()+"/"+"shared_prefs/ leads to /data/data/com.hirecraft.hirecraftmanager/files/shared_prefs/swipe_preferences.xml !!! The shared_prefs folder is not under files folder. Replace the getPath() with getParent(). Downvote because of your unfriendly attitude! – goseib Mar 22 '15 at 19:33