Share via

reading from a sqlite in a viewModel

Eduardo Gomez 4,316 Reputation points
2020-12-19T19:54:03.42+00:00

I am following the MVVM pattern for Xamarin forms, and for some reason, if I call my table in my VM, the count in 0 and I do not see anything in, but if I put that same line in the code behind, in the OnAppear, I set a breakpoint and I can see all my data

What is happening, can somebody explain?

this is my VM that read my things

public class AddressTableVM {
        public ICommand ToInputCommand { get; set; }
        public ObservableCollection<Address> MyAdresses { get; set; }
        public AddressTableVM() {

            GetValues();

            // Here we are using a lambda, to take us to the "Input address" when we touch the button on the toolbar

            ToInputCommand = new Command(async () => {
                await Application.Current.MainPage.Navigation.PushModalAsync(new InputAddress());
            });
        }

        private void GetValues() {

            MyAdresses = new ObservableCollection<Address>();

            using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation)) {

                conn.CreateTable<Address>();
                List<Address> addresses = conn.Table<Address>().ToList();

                foreach (var item in addresses) {

                    MyAdresses.Add(item);
                }
            }
        }
    }

View to read

<ContentPage.ToolbarItems>
    <ToolbarItem Text="Add a new address"
                 Command="{Binding ToInputCommand}"
                 Order="Primary" />
</ContentPage.ToolbarItems>

<CollectionView SelectionMode="Single" ItemsSource="{Binding MyAdresses}" >
    //To implement
</CollectionView>


public ICommand SaveCommand { get; set; }

        private Address _Address;
        public Address Address {
            get { return _Address; }
            set
            {
                if (_Address != value) {
                    _Address = value;
                    RaisePropertyChanged();
                }
            }
        }
        public InputAddressVM() {

            Address = new Address();

            SaveCommand = new Command(async () => {
                using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation)) {

                    conn.CreateTable<Address>();
                    int row = conn.Insert(Address);

                    if (row > 0) {
                        await Application.Current.MainPage.Navigation.PopModalAsync();
                    } else {
                        await Application.Current.MainPage.DisplayAlert("Error", "Something went wrong", "OK"); 
                    }
                }
            });
        }

insert is correct because I do not get any errors, and I Pop

Developer technologies | .NET | Xamarin

Answer accepted by question author

Cole Xia (Shanghai Wicresoft Co,.Ltd.) 6,756 Reputation points
2020-12-23T05:23:29.873+00:00

Hello,

Welcome to Microsoft Q&A!

I managed to reproduce your first problem.

1. The workaround is to call GetValues method inside OnAppearing instead of constructor of Viewmodel .
   protected override void OnAppearing()  
           {  
               base.OnAppearing();  
     
               var model = this.BindingContext as AddressTableVM;  
               model.GetValues();  
            
           }  

And initialize the List MyAdresses inside constructor of Viewmodel intead of GetValues method .

   public AddressTableVM() {  
     
               //GetValues();  
     
               MyAdresses = new ObservableCollection<Address>();  
2. When I was selecting item , no error happens , if you want to unselect the item , just set SelectedItem as null in ViewModel .

Thank you.


If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.