Storing data with SharedPreferences

Sometimes, an app needs to store data after it closes so that it can be retrieved later. This data is often very simple, so a database may be unnecessary.

How to do it...

There are two parts to using the ISharedPreferences instance: read and write. Both are similar but write has a few extra steps. Let's take a look at the following extra steps included:

  1. In order to either read from or write to the preferences, we have to first obtain the preferences by name:
    ISharedPreferences prefs = GetSharedPreferences(
      "MyPreferences", FileCreationMode.Private);
  2. Once we have the preferences, we can simply query a value using a key along with a default value:
    if (prefs.Contains("MyKey")) { int myIntValue = prefs.GetInt("MyKey", ...

Get Xamarin Mobile Development for Android Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.