Persisting Settings and Preferences in Mobile Apps with Xamarin.Essentials

Avatar

James

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:

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

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.

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.

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:

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.

Avatar
James Montemagno

Principal Program Manager, Mobile Developers Tools

Follow James   

No Comments.