5

I'm trying to delete my SharedPreferences, but it's not working: size is not set to 0 as I would expect.

SharedPreferences sp = context.getSharedPreferences(name, mode);
SharedPreferences.Editor e = sp.edit();
e.clear();
e.commit();
Map<String, ?> map = sp.getAll();
int size = map.size();

Any suggestions?

private static String name = "ABC_PREFS";
private static int mode = Context.MODE_PRIVATE;
gosr
  • 4,593
  • 9
  • 46
  • 82

3 Answers3

2

Your code looks fine from reading through it. Are you sure that context variable is initialized properly? Are other SharedPreferences variables pointing to the same file perhaps?

If these are not the problem, please consider taking a minimal sample app and paste this code in to see if it still fails. It is easier to fix a problem like this with the complete app than with just a code snippet.

gabriel
  • 1,163
  • 2
  • 9
  • 15
  • I think this is the closest I get to an answer I can use. I fixed it by using `App.getContext()` as context, where `App` is an Application class and the context in that is set at `onCreate()` in this class. So yes, it was a Context issue. Many points your way ;) – gosr Dec 02 '12 at 20:27
0

SharedPreferences.Editor.clear() just removes only values of your preferences is that not enough for you? You can remove all your entries with SharedPreferences.Editor.remove():

    for (String key: sp.getAll().keySet()) {
        e.remove(key);
    }
    e.commit();
nfirex
  • 1,523
  • 18
  • 24
-3

You can write size of map into shared preferences:

e.clear();
e.putInt("size", map.size());
e.commit();

To get size of map call:

int size = sp.getInt("size", 0);
Artyom Kiriliyk
  • 2,513
  • 1
  • 17
  • 21