10

from what I can incur out of the SharedPreferences documentation, I can update a preference, add one or clear all preference values in a shared preference file.

But I want to completely clear everything inside a shared preference file, not just the values, but the preferences they refer to as well.

Orca
  • 2,035
  • 4
  • 24
  • 39

2 Answers2

32

If you have a SharedPreferences.Editor object and you call clear(), does this not get you what you want? It will remove all preferences and if you call sharedPref.getAll() it should give you a map of size 0 [I just tested this].

To remove one specific preference, call editor.remove(pref), where pref is the preference name.

PS: Don't forget to commit your changes by calling commit() or apply() method on the editor. apply() is faster as it is asynchronous. commit() is synchronous but returns a boolean indicating if the commit succeeded.

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
antonyt
  • 21,863
  • 9
  • 71
  • 70
  • 1
    Well, the documentation says: " Mark in the editor to remove all values from the preferences. Once commit is called, the only remaining preferences will be any that you have defined in this editor. Note that when committing back to the preferences, the clear is done first, regardless of whether you called clear before or after put methods on this editor. " So it seems like removal of values, and I want to remove both the preferences and their values. Also, what if I wanted to remove just one preference and its value from a file? – Orca Sep 02 '10 at 19:52
  • 2
    clear removes everything, including the keys. What that is saying is that if you perform a clear on an editor object and then add some values before calling commit(), the values you just added won't be affected by the clear. Everything that was there before will be cleared, though. – QRohlf Sep 02 '10 at 19:56
  • The Editor class has a 'remove(String pref)' method too, so you can remove a single preference with it. – antonyt Sep 02 '10 at 20:04
  • 1
    Android's documentation on this is very unclear to me. Thanks for the clarification QRohlf. – Jeff Axelrod Oct 06 '10 at 04:20
1

you could try deleteFile to delete the sharedpreferences file in your app's private storage.

If you just want to delete the contents but not the file, calling .edit().clear().commit() should do it.

If just you want to delete one preference, calling .edit().remove("key").commit() should work.

Dhaval Parmar
  • 18,812
  • 8
  • 82
  • 177
QRohlf
  • 2,795
  • 3
  • 24
  • 27
  • Alright, but what if I wanted to remove one preference (and its value) from the file? – Orca Sep 02 '10 at 19:32