views:

62

answers:

2

Hello there, 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.

+1  A: 

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.

QRohlf
Alright, but what if I wanted to remove one preference (and its value) from the file?
Voulnet
See edits for how to do this.
QRohlf
Thank you so much!
Voulnet
+2  A: 

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.

antonyt
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?
Voulnet
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
The Editor class has a 'remove(String pref)' method too, so you can remove a single preference with it.
antonyt
Thank you two so much!
Voulnet
Android's documentation on this is very unclear to me. Thanks for the clarification QRohlf.
glenviewjeff