Search code examples
xamarin.formsrealmpicker

How to save piker's value to Realm db?


i am working with Realm and my example is similar to this one by @BenBishop . I added a Yes / No picker to my PersonPage and im trying to save the selected value of the picker to my db. Could anyone help me with that please? Thanks!


Solution

  • This is not really a Realm question as that sample just uses Realm internally for storage. Most of its code is generic C# Xamarin code.

    As a quick summary, you need to

    1. Add a property in AddEditPersonViewModel.cs
    2. Update AddEditPersonViewModel.Init to load the new property
    3. Add a picker mapped to that property, in PersonPage.xaml
    4. Add a matching property in Person.cs to store that value
    5. Update IDBService.SavePerson to allow passing the new property
    6. Update RealmDBService.SavePerson to copy the new property back to Realm

    In detail:

    // step 1 & 2
    public class AddEditPersonViewModel : INotifyPropertyChanged
    {
    ...
    // added property
        private int superPower;
    
        public int SuperPower {
            get {
                return superPower;
            }
            set {
                superPower = value;
                PropertyChanged(this, new PropertyChangedEventArgs("SuperPower"));
            }
        }
    ...
        public void Init (string id)
        {
        ...
            SuperPower = Model.SuperPower;
    
    
    
    // step 3 - in PersonPage.xaml
            Text="{Binding LastName}" />
          <Picker SelectedIndex="{Binding SuperPower}">
            <Picker.Items>
              <x:String>Flight</x:String>
              <x:String>Super Strength</x:String>
              <x:String>Ordinariness</x:String>
            </Picker.Items>
          </Picker>
        </StackLayout>
    
    
    // step 4 - in Person.cs
      public class Person : RealmObject
      {
      ...
          public int SuperPower { 
              get; 
              set;
          }
    
    
    // step 5 in IDBService.cs
        public interface IDBService
        {
            bool SavePerson (string id, string firstName, string lastName, int SuperPower);
    
    
    // step 6 in RealmDBService.cs
      public class RealmDBService : IDBService
      {
      ...
          public bool SavePerson (string id, string firstName, string lastName, int superPower)
        {
            try {
                RealmInstance.Write (() => {
                    var person = RealmInstance.CreateObject<Person> ();
                    person.ID = id;
                    person.FirstName = firstName;
                    person.LastName = lastName;
                    person.SuperPower = superPower;
                });