Ben's Series

Transcript

00:10

00:10

In this video, we’re going to take a look at how we can use the Xamarin Realm database to create a new record. If we take a look at our application in its current state, we’ll see that we don’t have any people to list out. Let’s go ahead and wire up our Add function.

00:29

00:29

I’m going to stop the simulator and then we’re going to take a look at our RealmDBSerivce. We’ll see that we don’t have anything implemented. Before we can start implementing the service, we first need to add the Realm NuGet packages, not only to our Forms PCL but also to our individual platform projects as well. I added it to iOS and now I’m going to add it to Android.

01:00

01:00

Now that we’ve added our NuGet packages, we can start updating our service and models to use Realm. The first thing I need to do is go into my Person model. As you can see it is very simple, it has a first name property as well as a last name property. I’m going to make our class extend RealmObject. This will basically allow us to save this object to our database for a later retrieval.

01:27

01:27

Now I’m going to go into my RealmDBService and I’m going to update SavePerson. Before I update SavePerson, I need to get an instance to Realm. I’m going to say This.RealmInstance = Realm.GetInstance. This is just going to be a nice, convenient reference that we can use locally. I’m going to make this protected in case I ever want to extend this class. I’m going to say RealmInsance.Write and we’re going to use a lambda expression for our action. We’re going to say, RealmInstance.CreateObject and we want to specify the type of object that we want to create. Right now we only have one, which is person. I’m also going to set this to a variable so I can then say person.FirstName = firstName and then I’m going to say person.LastName = lastName.

02:36

02:36

If I compile, I’m going to get a compile error because I need to return some sort of success boolean. For now, I’m just going to do a return true here and then I’m going to wrap this also in try/catch just in case we do something that we shouldn’t. At least we have an opportunity to do something about it or put a breakpoint here to see what’s going on. Now, if I compile our project, we have no problem.

03:06

03:06

Let’s take a quick look at our AddEditPersonViewModel. We’ll see that I have this SaveCommand. Our SaveCommand is basically just calling DBService.SavePerson. It’s grabbing the first name and last name of what we’ve entered. If we go into the XAML for the PersonPage, we’ll see that we bound to this command, like so. And now, if I run our application, we’ll again see our blank screen. I’m going to hit Add and type in Ben for the first name, Bishop for the last and hit create. Hopefully, we’ve done everything correctly and in the next lesson we’ll find out if we did indeed create this record correctly.