In this post, I’ll be covering shared preferences in Android, and how to use them in Xamarin Android.
What is a shared preference?
Shared preferences are basically small pieces of data that you can store on a users device that you can read from for certain information, like OAuth access tokens, app settings that you don’t want to have to save on a server, etc. This is basically the same thing as using cookies for a website, and it allows you to quickly access data without an internet connection.
Storing a shared preference
Shared preferences are managed by the
PreferenceManager class, which resides in the Android.Preferences namespace in Xamarin. To store a shared preference, you have to get an interface to the shared preferences, get and interface to the shared preferences editor, write out the data to shared preferences, and apply the changes with the shared preferences editor. This can all be done with the following code:
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(context); ISharedPreferencesEditor editor = prefs.Edit(); editor.PutString("someSortOfKey", "someValue"); editor.Apply();
In this code, we store a string to shared preferences with the key “someSortOfKey”, so anytime we query the preference managers default shared preferences, we can use this key to get the string we just stored. The types of data you can store in shared preferences are booleans, floats, integers, longs, strings, and ICollections of strings (so any collection type that implements the ICollection interface), and this makes good sense, because what other data would you ever need to be caching in this manner anyway?
Getting a shared preference
To get a shared preference is even easier than storing one:
var preferences = PreferenceManager.GetDefaultSharedPreferences(context); return preferences.GetString("preferenceKey", "");
Here, we simply get the default shared preferences from the preference manager, and use
Get<Type>, in this case
GetString, to get the shared preference. You may be wondering why I passed an empty string as the second argument to
GetString, that’s because the second argument is the default return value if the shared preference cannot be found, so by returning an empty string I can check what gets returned and act accordingly.
And that’s it, there’s not a lot to shared preferences, I suppose I could have bored you to death and gone through examples of storing every type of data a shared preference can be, but that is a little cumbersome and I think you get the idea. There is a little bit more functionality baked into the preference manager, but I’ve never found any use for said features, so I don’t know enough to speak on them. Hopefully this post was helpful, and if you like this content, consider following the blog as it helps me out a lot just knowing I have regular readers, also leave any feedback you have, I’d love to hear your thoughts. Thanks, and until next time.