Delete SharedPreferences File

后端 未结 4 1986
南方客
南方客 2020-12-05 05:21

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

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 05:51

    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.

提交回复
热议问题