0

How do i clear the entire shared preferences folder in the users sandbox not just default. The shared_pref folder is located here usually from adb shell:

/data/data/yourappsPackage/shared_prefs

So i have created many different shared prefs xml files.

for example i created them like this:

context.getSharedPreferences("pref_file1",Context.MODE_PRIVATE);
context.getSharedPreferences("pref_file2",Context.MODE_PRIVATE);
context.getSharedPreferences("pref_file3",Context.MODE_PRIVATE);

Now i would like to clear them all with a single command ? This is what i have tried so far: sharedPreferences.editor.clear() ; but doesn't this only clear the file that im currently using ?

I've tried:

preference=context.getSharedPreferences("pref_file1",Context.MODE_PRIVATE);
        preferences.edit().clear().commit();

and pref_file1 gets cleared but i need pref_file2 and pref_file3 to get cleared also.

j2emanue
  • 60,549
  • 65
  • 286
  • 456
  • Actually a `clear()` will remove them all. The `remove()` command is for specific preferences. – Jay Snayder Dec 08 '15 at 19:36
  • no , i jus tried it and clear removes all per file. I want to remove ALL files. – j2emanue Dec 08 '15 at 19:37
  • No need to do it by a specific sharedPreference. Get a hold of your shared preferences referenced by your application. `SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());` Then you can call clear on your preferences at this level. – Jay Snayder Dec 08 '15 at 19:40
  • Jay, i tried your solution on nexus 4 api 19 and it does not clear all the files in shared_pref. It only clears the default file. Did you actually try it ? – j2emanue Dec 08 '15 at 19:52
  • http://stackoverflow.com/questions/3687315/deleting-shared-preferences – Jimmy Dec 08 '15 at 20:11
  • @j2emanue I did not do a thorough test looking back at it. Ali seems to be on the best track that I can think of. Hopefully you don't have to do this on hundreds of files or you will take some serious hits working with preferences in this manner, heh. – Jay Snayder Dec 08 '15 at 20:36

1 Answers1

2

SharedPreferece is file, so behave it like file. Delete them by below function

void delSharedPref(){

File list = new File("/data/data/" + getPackageName() +  "/shared_prefs");
        File[] files = list.listFiles();
        for(int i = 0; i < files.length; i++ ){
            files[i].delete();
        }

}

Or

If you search about less code line use below code

File s = new File("/data/data/" + getPackageName() +  "/shared_prefs");
s.delete();
s.mkdir();
Ali
  • 508
  • 1
  • 5
  • 16
  • Thanks i thought of this way. this might be the only answer but i'll wait a few hours and see if anyone else a solution with less lines. Thanks. – j2emanue Dec 08 '15 at 19:53