Android Shared Preferences String Set
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 into a nightmare.

Cut the story short to save strings and most of the other data types in Shared Preferences we do this:

And to retrieve we simply use the get methods:

I used the same approach to save content from Notifications created within my application in order to build the Notifications again when the device is rebooted. It looked so simple:

It worked absolutely fine when I added and removed more such data from the Shared Preferences. As soon as I rebooted my testing device. BOOM!

Just a single String value was present in the SharedPreferences.

WHY SO?

As mentioned in the documentation:

You must not modify the set instance returned by the getStringSet call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.

Workaround

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

This can save you some precious hours which you’d otherwise spend scratching your head.

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

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