dotnetco.de

Store Lists in Xamarin Forms Settings Plugin

When storing settings in Xamarin Forms you are probably aware of SettingsPlugin provided by James Montemagno. If not, have a look at it! The plugin only supports simple data types like int, string, bool etc. but not lists. So if you want to store lists with the SettingsPlugin in your Xamarin Forms app you need to serialze them first. Here is a short example how to do it.

The following code could be used in your settings file. It will store and retrieve a list of Integers. I use standard Newtonsoft Json for (de)serializing so you have to add the Json Package and declare “using Newtonsoft.Json;” in your code. So the input and output is a list of integers, internally a string value is stored in the settings as this is of course supported by the SettingsPlugin.

If no list is stored yet, I return a empty list instead of null so you could always use e.g. “MyList.Contains(123)” and get a valid result even if your list is not created yet. Of course you could shrink the code if you like but it’s easier to debug in case of problems during setup.

private const string myIntListKey = "myintlist_key";

public static List<int> myIntList
{
  get { 
    string value = AppSettings.GetValueOrDefault<string>(myIntListKey, string.Empty);
    List<int> myList;
    if (string.IsNullOrEmpty(value))
      myList = new List<int>();
    else
      myList = JsonConvert.DeserializeObject<List<int>>(value);
    return myList;
  }
  set {
    string listValue = JsonConvert.SerializeObject(value);
    AppSettings.AddOrUpdateValue<string>(myIntListKey, listValue); 
  }
}

 

3 Comments

  1. very helpful, thanks. But the thing is when I’m using the add and insert methods to add a new item to the list, it is calling the get instead of set!!

    here is my code:
    //adding a new item to the list
    private void order(Sales_Order_Items sale)
    {

    Settings.Usercartlist.Add(sale);
    }

    //list property in settings file
    public static List Usercartlist
    {
    set
    {
    string listValue = JsonConvert.SerializeObject(value);
    AppSettings.AddOrUpdateValue(myIntListKey, listValue);

    }
    get
    {
    string value = AppSettings.GetValueOrDefault(myIntListKey, string.Empty);
    List myList;
    if (string.IsNullOrEmpty(value))
    myList = new List();
    else
    myList = JsonConvert.DeserializeObject<List>(value);
    return myList;

    }

    }

    Thank you in advance.

    1. Hi Mohammad,
      try creating an instance of your Usercartlist first, e.g. List myList = Settings.Usercartlist; myList.Add(sales);
      Would that fix it?

Leave a Comment