How to store simple Key-Value data?
How to store simple Key-Value data?
To store simple key-value data in a Xamarin.Forms application, you can use the Preferences
class provided by Xamarin.Essentials. This class allows you to save and retrieve application preferences in a key/value store, which is supported across multiple platforms including iOS, Android, and UWP.
Add Xamarin.Essentials to Your Project:
Ensure that Xamarin.Essentials is added to your project. You can do this via NuGet Package Manager in Visual Studio.
Initialize Xamarin.Essentials:
Initialize Xamarin.Essentials in your MainActivity
(for Android) and AppDelegate
(for iOS).
Android:
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.OS;
using Xamarin.Essentials;
[Activity(Label = "YourApp", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
}
iOS:
using Foundation;
using UIKit;
using Xamarin.Essentials;
[Register("AppDelegate")]
public class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
Xamarin.Essentials.Platform.Init(this, options);
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
Store a Value:
Use the Preferences.Set
method to store a value with a specific key.
using Xamarin.Essentials;
// Store a string value
Preferences.Set("username", "JohnDoe");
// Store an integer value
Preferences.Set("userAge", 30);
Retrieve a Value:
Use the Preferences.Get
method to retrieve the value associated with a specific key.
// Retrieve a string value
string username = Preferences.Get("username", "default_value");
// Retrieve an integer value
int userAge = Preferences.Get("userAge", 0);
Remove a Value:
Use the Preferences.Remove
method to remove a specific key and its associated value.
Preferences.Remove("username");
Clear All Values:
Use the Preferences.Clear
method to clear all stored preferences.
Preferences.Clear();
Here is a simple example demonstrating how to store, retrieve, and remove key-value data using Xamarin.Essentials Preferences:
...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào