Image for post
Image for post
Don’t stare at your code for too long.

A Nightmare with Shared Preferences and StringSet

I love using Shared Preferences to cache data just about everywhere in my Android Applications . Little did I know that storing values in a Set of Strings would turn in a nightmare.

Set<String> sets = new HashSet<>();
sets.add("notification title 1");
mSharedPreferences.edit().putStringSet("keySet",sets).apply();//And to add another local notification:sets = mSharedPreferences.getStringSet("keySet",new HashSet<String>());sets.add("notification title 2");mSharedPreferences.edit().putStringSet("keySet",sets).apply();


Create a copy of Set<String> every time the getStringSet returns that instance using:

Set<String> newSet = new HashSet<String>(mSharedPrefs.getStringSet("keySet", new HashSet<String>()));

Written by

Pouring thoughts in technology and code. Writer with over 2M views. An Android and iOS developer by the day. Sometimes funny.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store