I'm using Xamarin.Essentials to store user preferences for my application. I have a scenario where I want to store multiple preferences which I'm using "sharedName" for (see code below).
const string bShare = "BreakfastPrefs";
private bool _eggs;
private bool _bacon;
public bool Eggs
{
get
{
//load from prefs
return _eggs= Preferences.Get("EggSwitch", false, bShare );
}
set
{
//save to prefs
_eggs= value;
Preferences.Set("Eggswitch", value, bShare );
}
}
public bool Bacon
{
get
{
//load from prefs
return _bacon= Preferences.Get("BaconSwitch", false, bShare );
}
set
{
//save to prefs
_bacon= value;
Preferences.Set("BaconSwitch", value, bShare );
}
}
I was hoping that later on I could do something like 'Preferences.GetByShareName("bShare") to retrieve all preferences within that share. But it appears that I'm only to get each object back from the preferences one by one. I'm not really sure of the purpose of the shareName property of Preferences if I can't do this.
Here's an example of one of the Get method from Xamarin.Essentials.Preferences.
public static string Get(string key, string defaultValue, string sharedName);
Any help would be appreciated, the only other thing I can think of doing would be to store my Eggs and Bacon within one 'preference' as a delimited list, then when I want to retrieve it split it into a collection....but that feels a bit nasty.
Any input is appreciated. Thanks!
CodePudding user response:
The sharedName
parameter is not supposed to be used as a way to categorize your internal preferences. Its purpose is to enable sharing of preferences OS-wide so that an application can use preferences set by another application.
As for categorizing your preferences, if your requirements are simple, you can serialize your values to store a string with your bShare
as the key without specifying a sharedName
. Otherwise, I suggest using an actual local database instead.
CodePudding user response:
For anyone interested, I solved this by serializing my own Dictionary object which stores the key and value as JSON. This is then stored within a Xamarin.Essentials.Preferences object. I then deserialize as required.
Thanks for the input.