1

I want to clear all data from shared preferences.I tried the below code but it's not working.What wrong am I doing?

SharedPreferences preferences = context.getSharedPreferences("PREFERENCE", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Soham
  • 4,397
  • 11
  • 43
  • 71

3 Answers3

1

Make sure that 'PREFERENCE' is the name of preference that you want to clear.

Sunny Shah
  • 918
  • 1
  • 8
  • 8
1

This below piece of code helps me.I have to use PreferenceManager.

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();
        editor.clear();
        editor.commit();

Ah! Simple mistake.

Soham
  • 4,397
  • 11
  • 43
  • 71
0

You problem is how you get the preferences:

 SharedPreferences preferences = context.getSharedPreferences("PREFERENCE", 0);

You need to get ALL the preferences:

SharedPreferences preferences = getPreferences(0);

Now, to remove all the SharedPreferences use Editor.clear()

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.

SharedPreferences preferences = getPreferences(0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();

According documentation:

Returns a reference to the same Editor object, so you can chain put calls together.

I bet this will work also:

SharedPreferences preferences = getPreferences(0);
SharedPreferences.Editor editor = preferences.edit();           
editor.clear().commit();
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • SharedPreferences.Editor.clear() is showing `non-static method clear() cannot be called from static content` – Soham Aug 06 '15 at 12:04