Local Database with Realm – Xamarin.Forms

Realm is a very popular solution for mobile databases as it includes very nice features, it’s very quick and easy to use. It supports many platforms as well as Xamarin.

You can use realm with Xamarin.Forms after installing the nuget package. Be careful to install nuget package to Android, iOS and UWP seperate project.

Current realm version is 1.5. After choosing Realm package, nuget will also install all available requirements.

First of all in order to store items in the database, you should create a model which will represent the identity that you want to save. For example lets say that we want a Person identity so we will store Persons.

Lets create the necessary model for this case:

After that we  will create a test interface in which we can add some users and interact with realm.

 

To interact with the database lets create a RealHelper class which we will use to add persons and load.

 

In order to make a write operation we use a transaction and we do that by creating a write with beginWrite(). More information for the functions and how they operation can be found on the documentation.

 

 

 

The main logic comes from the two buttons:

 

Putting a breakpoint in the loadPersons button we can see the stored persons.

 

initialization issues I found:

  • In the UWP project you must install realm database nuget package and not realm nuget package. That’s because some functions don’t exist in the uwp apis so if you install realm package some exceptions will occur during the opening of the app.
  • Check if fody file exists in both iOS, Android and UWP projects and the its content should be

  • Be sure that all packages are updated across all projects and are the same version.

 

Leave a Reply

Your email address will not be published. Required fields are marked *