I'm creating a SharedPreferences
in my app using a dyanmic key generated using a combination of some fixed String and id(unique id for each item).
Get values from shared preference
public static int getSharedPref(Context context, String keyName) {
SharedPreferences betaPref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
return betaPref.getInt("getShare" keyName, 0);
}
Save value in shared preference
public static void saveSharedPref(Context context, int value, String keyName) {
try {
SharedPreferences betaPref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = betaPref.edit();
editor.putInt("getShare" keyName, value);
editor.apply();
} catch (Exception e) {
LogUtil.e("getShare" keyName, Log.getStackTraceString(e), e);
}
}
So far it works good, but now I also want to delete these shared preference when user logout from the app.
I know we can use
preferences.edit().remove("getShare").commit();
to remove a particular shared preference, but being a dynamic keys I don't have a exact name to delete it.
Query : Is there any way I can delete all shared preference containing a particular keyword? Or fetch all the keywords used in shared preference and filter them to delete on specific ones
CodePudding user response:
Removing all preferences:
SharedPreferences sharedPreferences = context.getSharedPreferences("name", Context.MODE_PRIVATE);
sharedPreferences.edit().clear().commit();
Removing single preference:
SharedPreferences sharedPreferences = context.getSharedPreferences("name", Context.MODE_PRIVATE);
sharedPreferences.edit().remove("key_name").commit();
SharedPreferences
has the method getAll()
that returns a Map<String, ?>
. From the Map you can retrieve easily the keys with keySet()
and the key/value mappings with entrySet()
:
Map<String, ?> allEntries = prefA.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.d("map values", entry.getKey() ": " entry.getValue().toString());
}