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", 0);
    }
  3. 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);
    ISharedPreferencesEditor editor = prefs.Edit();
  4. Once we have the editor, we can write or update the values in the preferences instance using one of the various "put" methods:
    editor.PutInt("MyKey", myIntValue);
  5. The last thing there is to do is to save the changes made with the editor:
    editor.Commit();

How it works...

The ISharedPreferences type provides a general framework that allows us to save and retrieve persistent key-value pairs of primitive data types. We can save any primitive data types, such as bool, float, int, long, and string. This data will persist across user sessions, even if our app is killed.

There are two basic ways to obtain an ISharedPreferences instance:

  • Using the GetSharedPreferences() method on a Context, which provides a named preferences
  • Using the GetPreferences() method on an Activity, which provides an activity-based preferences

When obtaining a preferences instance, there is an additional argument passed, FileCreationMode. This argument determines where the preferences can be accessed from. Usually only FileCreationMode.Private is needed.

When we want to write values to the preferences, all we have to do is obtain an ISharedPreferencesEditor instance. We then use that editor to put our values, by key, into the preferences, ensuring that we commit our changes.

We don't always have to write our changes every time something needs to be updated. We can improve performance if we read out the values when the activity is created and only write them back when the activity is stopped.

Tip

Performance can be improved by saving and retrieving values from the preferences only when necessary.

There's more...

Shared preferences are not strictly used for saving "user preferences," such as what ringtone a user has chosen. If we need to include user preferences for our app, we can make use of the PreferenceFragment or PreferenceFragmentCompat instances. This provides a framework through which we can create user preferences, which will be automatically persisted (using shared preferences).

When creating a preference activity, we first create the XML representation of the screen hierarchy. In this case, it is just a single screen with a single preference, preferences.xml, saved in the XML resource folder:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
  <EditTextPreference
    android:defaultValue="anonymous"
    android:dialogTitle="User Name"
    android:key="UsernameKey"
    android:summary="Your user name."
    android:title="User Name"/>
</PreferenceScreen>

To support the older version of Android, we can use the Xamarin Support Library Preference v7 Component or NuGet. We then create a fragment, which inherits from the PreferenceFragmentCompat type, which will inflate the XML into a UI layout:

class SettingsFragment : PreferenceFragmentCompat {
  public override void OnCreatePreferences(Bundle b, string root) {
    AddPreferencesFromResource(Resource.Xml.preferences);
  }
}

We can now display that fragment in any activity, but typically we would create a settings activity. One thing that we do need to do when using the support libraries is to ensure that we specify the preferenceTheme value for the activity theme:

<resources>
  <style name="PrefsTheme" parent="@style/Theme.AppCompat">
    <item name="preferenceTheme">
    @style/PreferenceThemeOverlay</item>
  </style>
</resources>

To make use of the preferences, we use the PreferenceManager type. This is similar to getting an activity's shared preferences:

var prefs = PreferenceManager.GetDefaultSharedPreferences(this);
var username = prefs.GetString("UsernameKey", "anonymous");

A preference fragment is just an extension of the base Fragment type and can be used like any other fragment. No UI is specified as the UI is created from the preference XML resource. The activity that holds the fragment can be displayed as any other activity.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.143.239