Delete SharedPreferences File

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.


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.