Thursday, 17 May 2018

Simple App Data

IOS, Droid and UWP all have their own Key-Value paired dictionaries for storing simple data; generally application preferences, but the dictionary can be used to store application data if it's simple enough.
  • IOS: CFPreferences
  • Droid: Preferences
  • UWP: Application Data
Luckily there's also a Xamarin cross platform Nugget solution "Xam.Plugins.settings", install this package into our Portable Class Library (PCL), to leverage cross platform

PM> Install-Package Xam.Plugins.Settings

this Xamarin package abstracts the three platform specific solutions into a write once, use everywhere approach
  • IOS:NSUserDefaults
  • Droid: SharedPreferences
  • UWP: IsoltatedStorageSettings/ApplicationDataContainer
This does limit us to our basic types with a string key
  • Boolean
  • Int32
  • Int64
  • Float
  • Double
  • Decimal
  • Guid
  • String
  • DateTime
Let's take a look this simple UI

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:pav02.SimpleData"
             x:Class="pav02.SimpleData.MainPage">

    <StackLayout>
        <Entry x:Name="FullName_ENTRY" Placeholder="full name"/>
        <Button Text="Save" Clicked="Button_Clicked" />
    </StackLayout>
</ContentPage>


With the corresponding CodeBehind

using Plugin.Settings;
using System;
using Xamarin.Forms;

namespace pav02.SimpleData
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            var fullName = CrossSettings.Current.GetValueOrDefault("fullName", "");
            FullName_ENTRY.Text = fullName;
        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            var fullName = FullName_ENTRY.Text;
            CrossSettings.Current.AddOrUpdateValue("fullName", fullName);
        }
    }
}


We simply store our value in the CorssSettings.Current singleton instance of our unified application settings solution. when saving or retrieving data this way under the hood each platform calls their corresponding Settings solution.