George M Ceaser Jr
George M Ceaser Jr

Reputation: 1769

Export / Import Xamarin.Essentials Preferences

I was looking for a quick / simple way to import and export the Preferences object exposed by Xamarin.Essentials. Any suggestions?

Upvotes: 1

Views: 428

Answers (2)

George M Ceaser Jr
George M Ceaser Jr

Reputation: 1769

So I was not able to find a built in way to do this. I had to manually write code in my app to go through all my preferences, serialize them and them write the string to disk. Likewise for import I had to take a serialized string, reserialize it and then manually place the values back in my preferences.

Upvotes: 0

Cherry Bu - MSFT
Cherry Bu - MSFT

Reputation: 10346

According to your description, you want to save data in preference and get data from Preferences, am I right? if yes, please take a look the following code:

using Xamarin.Essentials;
  private void Btn1_Clicked(object sender, EventArgs e)
    {
        Preferences.Set("key1", "this is test");
    }

    private void Btn2_Clicked(object sender, EventArgs e)
    {
        var myValue = Preferences.Get("key1","");
    }

More detailed info about Xamarin.Essentials: Preferences, please take a look the following article:

https://learn.microsoft.com/en-us/xamarin/essentials/preferences?tabs=android

https://www.c-sharpcorner.com/article/xamarin-forms-application-preferences-using-xamarin-essentials/

Update:

If you want to save everything in Preferences, I suggest you can Serialization the data you want to save and deserialization the data that you want to get using Newtonsoft.Json.

Firstly, install Newtonsoft.Json by Nuget package, then do this:

public partial class Page13 : ContentPage
{
   public List<person> persons { get; set; }
    public Page13()
    {
        InitializeComponent();
        persons = new List<person>()
        {
            new person(){username="cherry",age=12},
            new person(){username="barry",age=14}
        };

    }

    private void Btn1_Clicked(object sender, EventArgs e)
    {
        string list = Newtonsoft.Json.JsonConvert.SerializeObject(persons);
        Preferences.Set("key1", list);
    }

    private void Btn2_Clicked(object sender, EventArgs e)
    {
        var myValue = Newtonsoft.Json.JsonConvert.DeserializeObject<List<person>>(Preferences.Get("key1", "")) ;
    }    
}


public class person
{
    public string username { get; set; }
    public int age { get; set; }
}

I use List to do example, but you can Serialization evertthing object to string, then save this string in Preference, deserialization string in to object to get data.

Upvotes: 1

Related Questions