Do the same thing as clear data button

2020-04-26 02:22发布

问题:

Is there a way to do the same thing that does clear data button from Settings->Application->Manage Applications to an application programmatically?

Or else i want on click to delete all sharedpreferences. How to do that?

回答1:

To delete all your application preference SharedPreferences.Editor.clear() method. See this documentation for details.



回答2:

What many users on Stackoverflow don't understand is; you want to delete ALL the shared preferences files. You don't want to clear them one by one.

You can simply delete all the files from your shared preferences folder:

    Context r = getActivity(); 
    File dir = new File(r.getFilesDir().getParent() + "/shared_prefs/"); // files directory is a sibling of the shared_prefs directory
    String[] children = dir.list();
    for (String aChildren : children) {
        r.getSharedPreferences(aChildren.replace(".xml", ""), Context.MODE_PRIVATE).edit().clear().commit();
    }
    try {
    Thread.sleep(800);
    }
    catch (InterruptedException e) { }
    for (String aChildren : children) {
        new File(dir, aChildren).delete();
    }
}

Also check these answers for more information and other ways of deleting shared preferences.