How can we store and retrieve App settings as key,value pair in Xamarin.Forms? Like when the app is closed we can store the user preferences and on restarting of the App we
The Application object (in VS you get an App class that inherits from it, I think the Xamarin Studio template might be slightly different) has a Properties dictionary that is specifically for this. If you need to make sure your properties get saved right away, there is a Application.SavePropertiesAsync method you can call.
I use Settings Plugin for Xamarin And Windows for Xamarin.Forms, the upside since this is implemented at the device-level, you can access these settings from any Forms project, PCL library OR your native project within your app.
private const string UserNameKey = "username_key";
private static readonly string UserNameDefault = string.Empty;
public static string UserName
{
get { return AppSettings.GetValueOrDefault<string>(UserNameKey, UserNameDefault); }
set { AppSettings.AddOrUpdateValue<string>(UserNameKey, value); }
}
It can be done this way too using Properties Dictionary
for storing data:
Application.Current.Properties ["id"] = someClass.ID;
for fetching data:
if (Application.Current.Properties.ContainsKey("id"))
{
var id = Application.Current.Properties ["id"] as int;
// do something with id
}
ref: https://developer.xamarin.com/guides/xamarin-forms/working-with/application-class/#Properties_Dictionary
You can use the preferences included with Xamarin.Essential.
/* You need to using Xamarin.Essentials
If you do not have Xamarin.Essentials installed,
install it from (NuGet Package Manager)
*/
// Add a reference to Xamarin.Essentials in your class
using Xamarin.Essentials;
// To save a value for a given key in preferences
Preferences.Set("my_key", "my_value");
// To retrieve a value from preferences or a default if not set
var myValue = Preferences.Get("my_key", "default_value");
// To check if a given key exists in preferences
bool hasKey = Preferences.ContainsKey("my_key");
// To remove the key from preferences
Preferences.Remove("my_key");
// To remove all preferences
Preferences.Clear();
Have a look at this link: https://docs.microsoft.com/en-us/xamarin/essentials/preferences?tabs=android