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:
- 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);
- 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", 0); }
- To write values to the preferences, we request the ability to edit it using the
Edit()
method of the instance:ISharedPreferences prefs = GetSharedPreferences( PreferencesName, FileCreationMode.Private...