Master Your Realm Xamarin – Get All the RealmObjects

In this lesson

  • Bind ListView to ViewModel
  • Update DB Service to return all RealmObjects
  • Add Init method to ViewModel



Now that we’ve successfully extended RealmObject and wrote an instance of our Person RealmObject to our device local storage, let’s explore displaying all of our RealmObjects inside a Xamarin.Forms ListView.


If we take a look at our PeopleListViewModel, we’ll see that we have an ObservableCollection called People. In our People page XAML, we’re going to bind to this ObservableCollection through our ItemSource property in our ListView. Next we’re going to set up our data template for our ListView. Here I’m just going to use a simple text cell. I’m going to bind its text to our FirstName for now. I’m going to instantiate the People ObservableCollection and I’m going to do this by wrapping our results from our DBService with an ObservableCollection.


If we go into our RealmDBService, we’ll see that our GetPeople method is not implemented. Let’s go ahead and change that. I’m going to get our RealmInstance. I’m going to ask for all persons. I’m going to use Link to convert this to a list. I’m going to remember to return it. Now if we run our application, let’s see what happens.


Now, we’ll see that we’re listing the two instances that I’ve created over the course of development of this application. If I enter in a new person and hit create and come back, we’ll see that we don’t see our new person. That’s because we need to refresh our ObservableCollection of people.


To do this I’m going to move our instantiation of the people ObservableCollection into it’s own method called init, which is short for initialization. I’m going to make this public. Now, if I go into my People page code behind, I can reference this initialization function via our OnAppearing method, like so.


In here, I’m going to make sure our binding context is not null. In this case, our binding context is our PeopleListViewModel. I’m going to cast our binding context and I’m going to call the initialization function like so. I’m going to run our application. We can see the previous record that we just entered. If I hit add and I type a new name, like my brother, hit create and then go back, we will see Zack now appears in our ListView.


One of the last things that we want to do is update our ListView to actually show something other than the first name. I’m going to recreate this real simple getter for FullName. I’m going to use string format where I’m going to pass in two entities to format, FirstName and LastName. I’m going to update our binding and now when I run the application we should now see full names in our ListView.


As you can see it’s real easy to use Realm Xamarin to retrieve any sort of records, or in this case, RealmObjects that we have written to our device’s local storage.

Additional Info

Register to get access to additional resources and info.