In today’s article, I will discuss how to use the Preference in storing data. Preference is one of the different data storage strategies that Xamarin provides. It is primarily used to store small amount of data like user settings of your Mobile Application. The preference is a key value pair structure where it can only cater to simple or intrinsic data types (e.g. strings, int, bool).
I will be using Xamarin Forms PCL type project and the sample application should be able to save the color that the user enters to the Application Preference and load it back to the Background Color property of the Application. We will target the Android platform and the UWP platform as shown in Figure 1 and Figure 2.
Keep in mind that the implementation of saving in preference is different per platform. Android uses Shared Preference, iOS uses NUserDefaults and UWP uses Local Settings.
First, let’s create a blank Xamarin Forms Project and choose a PCL type of project then create our simple UI with their corresponding button event handlers as shown in Figure 3.
Next, we create our interface in order to use platform specific preference operations for our different platforms as shown in Figure 4.
We then add per platform the Implementations of our IPreference Interface:
Important notes on the Android Implementation:
- IPreference implementation should be registered with the Dependency service with the metadata attribute.
- Android implementation uses the GetSharedPreference with two parameters: the name of settings and the type of the File Creation, which is in our case private, meaning our application can only access the said file.
Important note on UWP Implementation:
- Unlike the Android and iOS platforms, the implementation of IPreference in the App.xaml.cs should be registered in UWP as shown in Figure 7.
- UWP Implementation uses the local settings which is different from Android’s implementation of Key-Value pair style. It is like using sessions in MVC and Web Forms.
Next, we need to create another class that will act as a wrapper to our PreferenceService called SettingService as shown in Figure 8.
Then in order to consume our SettingService, we create a static property in our App.Xaml.cs file called Setting which will be using in our MainPage.xaml.cs file. as shown in figure 9.
Then lastly let’s put some code behind in our MainPage.xaml.cs to save and load in our preference as shown in Figure 10.
Try to build and run our Android and UWP application. We expect that the output should be the same with Figure 1 and 2.
We learned how to utilize the Application Preference in Xamarin forms for both Android and UWP platforms. Keep in mind that you should only store small data in preferences with intrinsic data types only. We also tackled Dependency Service in order to implement it to different platforms. In my next article, I will discuss the second strategy on data storage which is file storage.
Happy Coding 🙂