Realm is an object oriented database that can be use to handle data persistance in mobile apps. Is a solid alternative to SQLite and other mobile data persistance options.

The main reasons to use Realm are:

  • Ease of use : As Realm being an object oriented database, is really easy to manipulate.
  • Faster queries : Realm provides results relatively faster than SQLite
  • Synchronization : With the release of Realm Cloud Platform is pretty easy to handle the data synchronization.
  • There are two ways you can use Realm:

  • Using a local database: This data only will persist in your local device.
  • Using the Realm Cloud: This data will persist in the cloud and it will be synchronized with your local database.
  • In this series of articles I’m going to show you:

  • The basics when using Realm as local database
  • Some more advanced topics and tips
  • Realm Cloud Platform synchronization
  • Properly structure your project to work with Realm as local database and support synchronization.
  • In this specific article will be covering the basics on setting up Realm and starting to use it in Xamarin Forms.

    Let’s set up our project

    1-Download the Nuget Package

    Go to the nuget packages and install the realm package in all your solutions

    2-Configure project

    After install the project, it will automatically will add a file called FodyWeavers.xml (if not you will have to add it manually).
    In this file you will have to add the RealmWeaver reference.

    Let’s start with the basics

    To explain the main syntax we will create a todo list app sample.

    1-Create an object

    To create an object in Realm you just have to create a normal class that extends from RealmObject.

    Considerations:

  • If you want to ignore a property persistance so that it isn’t save in the database, you can add the attribute [Ignore] on top the property
  • To handle datetimes you have to use DateTimeOffSet instead of DateTime.
  • Realm does not allow models to be further subclassed in any way. The weaver will fail if it detects a class that inherits indirectly from the RealmObject class.
  • 2-Use Realm

    To add/delete/update or do any operation of realm, first you need a Realm instance.

    var _realm = Realm.GetInstance();
    

    3-Add elements

    4-Delete elements

    5-Update elements

    Let’s do a Todo list app

    1-Adding the UI

    Code here:

    2-Adding the ViewModel and wiring up

    Code here:

    Result:

    via GIPHY

    Full code:
    https://github.com/rdelrosario/RealmSample.git

    Happy data persistance!

    References
    https://blog.xamarin.com/cross-platform-development-with-xamarin-forms-and-realm/
    https://www.moveoapps.com/blog/getting-started-with-realm-database-better-alternative-to-sqlite/
    https://realm.io/docs/dotnet/0.73.0/#supported-types

    Categories:Android Blog Database iOS Samples Xamarin Xamarin Forms