1

Is it possible to programmatically delete all sharedPreferences of an Android application, without knowing the file names? I mean all files, not all keys of a given file.

I'm running unit tests with instrumentation for several applications, and i need to clear every file the an app may create under /data/data/app.package.name/shared_prefs folder.

For example an app may create these files under shared_prefs:

appname.xml
app.package.name_preferences.xml
app.package.name_tips.xml

while for another app i could have:

app.package.name_prefs.xml
app.package.name_foo.xml

Note: Using pm clear YOUR_APP_PACKAGE the app crashes.

Thanks

mcns7
  • 56
  • 1
  • 10
  • @codeMagic why duplicate? Actually i asked a different question from the one you linked – mcns7 Jun 12 '15 at 22:10
  • The accepted answer tells you how to clear the preferences which is what you are asking to do – codeMagic Jun 12 '15 at 22:54
  • post edited. Here i found what i was looking for: [http://stackoverflow.com/a/9073473/4512309](http://stackoverflow.com/a/9073473/4512309) – mcns7 Jun 13 '15 at 18:05

1 Answers1

3

To remove all prefs of the application you can use:

SharedPreferences.Editor.clear()

After that you have to commit() the removal.

So it would look like that in full code:

getSharedPreferences(PREFS, 0).edit().clear().commit() // change PREF to yours
mrtn
  • 889
  • 6
  • 12
  • 1
    By doing this i need to specify PREFS, but i don't know the filename in advance, i need to clear all preference files – mcns7 Jun 12 '15 at 21:20
  • Then you can try to use `getDefaultSharedPreferences(context)`: `getDefaultSharedPreferences(getApplicationContext()).edit().clear().commit();` – mrtn Jun 12 '15 at 21:23
  • Only `app.package.name_preferences.xml` gets cleared, other xml files are still untouched. – mcns7 Jun 12 '15 at 22:04
  • .xml? I thought you just wanted to remove all saved shared preferences? Now I see, you edited your questions... – mrtn Jun 12 '15 at 22:12
  • Aren't those "shared preferences" too? I thought that anything inside /shared_pref would be considered shared preferences. Android is a bit confusing sometimes.. – mcns7 Jun 12 '15 at 22:24
  • @mcns7 What other xml files do you want to delete? – codeMagic Jun 13 '15 at 01:40
  • 1
    every file that an application may create inside `/data/data/shared_prefs`, i don't know filenames though, my code will test several applications – mcns7 Jun 13 '15 at 08:33