Delete SharedPreferences File
Asked Answered
B

6

28

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?"

Bandaid answered 25/5, 2011 at 13:34 Comment(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.Lilia
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.Giza
C
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.

Choreography answered 25/5, 2011 at 13:40 Comment(9)
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. thanksBandaid
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: developer.android.com/reference/java/io/…. Its quite easy: File file= new File("/data/data/.../shared_prefs/X.xml"); and then file.delete();Choreography
You can delete programmatically the shared preferences file on non-routed devices?Karney
The answer to my above question is: NO.Karney
@Karney Deleting programmatically seems to work for me (Nexus 7, not rooted, signed app). But have not checked with app submitted to store yet...Giza
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.Choreography
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).Nickola
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 :-/Fancie
If delete == true, file still existAlbaalbacete
H
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.

Heller answered 1/7, 2013 at 11:29 Comment(3)
Best answer that i found so farPilarpilaster
Can't rely on hard coded paths. Who knows what Google may change in the next android version. :(Bibeau
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!Something
A
11

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()
        }
    }
}
Agricola answered 21/5, 2021 at 8:40 Comment(1)
Do not use apply(), it may cause race condition. Use commit() instead.Bibeau
D
10
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);
    }
}
Deathful answered 28/3, 2017 at 23:42 Comment(2)
What is FileUtils?Oration
@Oration FileUtils utility class from Apache Commons IO library. implementation 'commons-io:commons-io:2.6Alansen
F
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();
Flight answered 25/5, 2011 at 13:34 Comment(2)
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.Caulescent
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!Caulescent
N
0

I found (in Android 12, years after the original question), that if I delete the shared prefs file shortly after some code edits a pref value, applying the new pref might not finish until after I delete the file, at which point Android will recreate the file with all the previous values intact.

This also happened when I followed the recommendation from @inazaruk to clear the prefs before deleting the file, because I used apply() there. Perhaps that wouldn't cause a problem if I used commit() instead, but I found that clearing the prefs wasn't needed in my case.

Nickola answered 28/11, 2023 at 23:36 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.