How to clear Shared Preferences for Logout?

2.7k Views Asked by At
public class Session {

    public static void setDefaults(String key, String value, Context context) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(key, value);
        editor.commit();
    }

    public static String getDefaults(String key, Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(key, null);
    }

    public static void removepreferences(String key,Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();
        editor.clear();
        editor.commit();

    }

}
2

There are 2 best solutions below

0
On

you can remove the sharedpreference data from this.

SharedPreferences preferences = getSharedPreferences("Mypref", 0);
preferences.edit().remove("shared_pref_key").commit();
0
On

Try this one and enjoy

Session.setDefaults(Your key, "", context);