Persisting Settings and Preferences in Mobile Apps with Xamarin.Essentials

James Montemagno

An essential part of any mobile application is the ability to persist data. Sometimes that is a large amount of data that requires a database, but often it is smaller pieces of data such as settings and preferences that need to be persisted between application launches. This is where Xamarin.Essentials can help out with its wide range of cross-platform APIs for mobile apps. Specifically, the Preferences API enables you to store application preferences in a key/value store. Let’s take look.

Setup

To get started with Xamarin.Essentials you need to install the NuGet package. Use Xamarin.Essentials for your .NET Standard library if you are using one to share code across your iOS, Android, and UWP app projects.

After installing the NuGet, there is a small amount of code on Android that is required to initialize Xamarin.Essentials.

In the Android project’s `MainLauncher` or any `Activity` that is launched, Xamarin.Essentials must be initialized in the `OnCreate` method:

protected override void OnCreate(Bundle savedInstanceState) {
  //...
  base.OnCreate(savedInstanceState);
  Xamarin.Essentials.Platform.Init(this, savedInstanceState); // add this line to your code, it may also be called: bundle
  //...

To handle runtime permissions on Android, Xamarin.Essentials must receive any `OnRequestPermissionsResult`. Add the following code to all `Activity` classes:

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
  Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

  base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

There are no permissions needed for the `Preferences` API, but it is still be practice to have this code in your project.

Save a Preference

Each preference has a unique key that is used to save and retrieve it. This single method supports passing several different data types including bool, double, int, float, long, string, and DateTime.

Preferences.Set("my_key", "my_value");

Retrieve a Preference

When you retrieve a preference you will use the same key that was used when saving it. Additionally, you will need to specify a default value in case the key doesn’t exist.

var myValue = Preferences.Get("my_key", "default_value");

Preferences and Data Binding

Xamarin.Essentials can be used with any Xamarin application, but if you are using an MVVM framework with your application such as using Xamarin.Forms you may want to add some data binding. It is straightforward to implement this with a few lines of code:

const string ActiveKey = "is_active_key";

public bool IsActive
{
    get => Preferences.Get(ActiveKey , false);
    set
    {
        if (IsActive == value)
            return;

         Preferences.Set(ActiveKey , value);
         OnPropertyChanged(nameof(IsActive));
    }
}

There you have it! With only a few lines of code, you can persist data in all of your apps. Remember that these settings are stored in clear text, so don’t store any user sensitive information. If you are in need of storing information in the device’s keystore/keychain then take a look at secure storage API in Xamarin.Essentials.

See It In Action

Each week on The Xamarin Show on YouTube and Channel 9, we highlight how to set up, get started, and use the APIs in Xamarin.Essentials. Check out this episode on Preferences:

Learn More

Browse through the Xamarin.Essentials documentation to learn more about all of the great cross-platform native APIs. Be sure to check out the Preferences documentation to learn of the APIs available, additional implementation, and limitation details. Xamarin.Essentials is also open source on GitHub where you can report issues, ask for features, and contribute to the library.

4 comments

Discussion is closed. Login to edit/delete existing comments.

  • Donald Pedder 0

    This is awesome! Implemented and working first go effortlessly. Thank you!

  • Don Glover 0

    Excellent. Exactly what I needed.

  • Gerry h 0

    The OnRequestPermissionsResult() method is never called, and the part “[GeneratedEnum]” causes a compile error. I am currently having to manually add “Storage” permission to my app, really hoping to find a way around this as my app absolutely requires the ability to store user preferences.

Feedback usabilla icon