For enquiries call:

Phone

+1-469-442-0620

HomeBlogothersIntegrating Realm with Xamarin (Includes Realm Sync)

Integrating Realm with Xamarin (Includes Realm Sync)

Published
05th Sep, 2023
Views
view count loader
Read it in
5 Mins
In this article
    Integrating Realm with Xamarin (Includes Realm Sync)

    When it comes to mobile applications with database support, the first thing that comes to mind is SQLite. However, there are a few drawbacks with SQLite such as no support for data encryption and low performance when dealing with large data.
    In this article, we take a closer look at Realm, a non-relational database and a solid replacement for SQLite and core data. It is quite efficient and works seamlessly even with a large amount of data.

    Integrating Realm with Xamarin

    Why use Realm

    • Easy to use 
    • Provides data synchronization 
    • Fast and Efficient 
    • Provides Encryption of data 

    Ways of using Realm 

    1. Using realm locally: This creates a local file in your mobile app. 
    2. Using realm cloud: The data lives in realm cloud and will be synchronized with the local database. 

    In this article I will show how to integrate realm in the Xamarin Forms project. I will also show how to use realm as local database(Part-1) and realm cloud(Part-2

    Prerequisites 

    1. Visual Studio 2015 Update2 or higher for windows 
    2. Visual Studio for Mac 7.0 or higher 

    Part-1: Using Realm Local Database 

    1. Firstly, create a Xamarin Forms project in Visual Studio for Windows or Mac. 
    2. Go to the NuGet packages and install the realm package in all your solutions. Always prefer to install the latest one. 
    3. It automatically adds fodyweavers.xml. If not added, please add it manually in all your projects.  

    Go to PCL project>—>Right click—>Add—>New File—>XML File—>FodyWeavers.xml 

    Go to Android project>—>Right click—>Add—>New File—>XML File—>FodyWeavers.xml 

    Go to iOS project>—>Right click—>Add—>New File—>XML File—>FodyWeavers.xml 

    Add the below code in the file
    FodyWeavers.xml 

    <? xml version="1.0" encoding=" utf-8" ?> 
    < Weavers> 
    <RealmWeaver /> 
    </Weavers> 

    Let's create a model 

     public class Animals: RealmObject 
    { 
            public string Name { get; set; } 
            public int Age { get; set; } 
    } 

    Opening Realms  

    Opening a Realm can be done by instantiating a new Realm object.  

    // Get a Realm instance  
    var realm = Realm.GetInstance(); 

    Note: If nothing is passed, it creates the default realm. You can add realm name as below 

    var realm = Realm.GetInstance(“Animals”); 

    This will create realm db with “Animals” name 

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

    1) Add elements 

    var _realm = Realm.GetInstance(); 
    Add elements 
    _realm.Write(() => 
                        { 
                            var entry = new Todo{ Name = “Dog”, Age =3 }; 
                            _realm.Add(entry); 
                        }); 

    2) Delete elements 

     var param = _realm.All<Animals>().First(b => b.Name == “Dog”);  
    using (var trans = _realm.BeginWrite())  
                    {  
                        _realm.Remove(param); 
    trans.Commit();  
                    }   

    3) Update elements 

     _realm.Write(() => 
                        { 
    param.Name = “Cat”; 
                            _realm.Add(param); 
                        }); 

    Part-2: Using Realm Cloud 

    Now let's see how to use realm cloud. The setup is still the same. Here we need a few more additional steps. 

    1) Create an account in realm cloud at

    (one-month free trial account).  

    2) Create an instance in realm cloud by clicking on create an instance 

    This instance ID will be further used for authentication  

    There are two types of Realm sync 

    1. Full Sync: All the data present in the cloud will be synced locally 
    2. Query Based Sync: Only partial data i.e the result set that is queried will be synced into the local copy. 

    Here I am going to show you how to use full sync as Realm recommends using Full sync. 

    Client Authentication:  

    Realm supports two types of authentication 

    1. Simple Authentication: To simply get started one can use simple authentication which uses username, password and other one is anonymous login. 
    2. JWT Authentication: It is recommended to use JWT Authentication for a better experience. 

    The below code shows how to use simple authentication with username and password. 

     var authUrl = new Uri("https://myinstance.cloud.realm.io"); 
    var credentials = Credentials.UsernamePassword(username, password, createUser: false); 
    var user = await User.LoginAsync(credentials, authUrl); 

    To authenticate, you must supply a server URL. This is the base URL for your server, such as https://myinstance.cloud.realm.io 

    Note: Here “myinstance" would be the instance id that you generated while creating your account  

    Create Realm through realm studio or through code. If the realm has not been created, while calling the realm instance it will automatically create. If you have already created through realm studio, you can just call the instance. 

    Example: 

    public static string realmPath = "realms://instanceId/realmname; 

    Here the realm path consists of instanceId followed by realm name. Something like this 

    public static string realmPath = "realms://instanceId/Animals; 

    Now let’s login and call realm instance 

    public async Task GetInitialize()
    {
    await StartLoginCycle();
    }
    private async Task StartLogin()
    {
    do
    {
    await Task.Yield();
    }
    while (!await LogIn());
    }

    //Call the login method

    private async Task<bool> LogIn()
    {
    try
    {
    user = User.Current;
    if (user == null)
    {
    var username = "DevUser"; //Pass your username
    var password = “User123"; //Pass the password
    var credentials = Realms.Sync.Credentials.UsernamePassword(username, password);
    /// Log in as the user.
    user = await User.LoginAsync(credentials, new Uri(RealmConnectionString.AuthUrl));
    }
    Debug.Assert(user != null);
    Console.WriteLine("Login successful.");
    await GetDataFromRealm();
    return true;
    }
    catch (Exception ex)
    {
    ///await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
    return false;
    }
    }

    //Call or create realm instance: 

    public static async Task GetDataFromRealm() 

    { 
                    var configuration = new FullSyncConfiguration(new Uri(realmPath, UriKind.Absolute), user); 
                    Var   _realm = await Realm.GetInstanceAsync(configuration); 
                 var param = _realm.All<Animals>(); 
    //Adding/updating/deleting operations are same as above 
    } 

    Conclusion

    In the above sections, we have seen how to integrate realm local db and realm cloud into your xamarin forms project. You will also be able to perform operations like adding items, updating items and deleting items (showed in Part-1). These code snippets are the same for realm local database and realm cloud. 

    You can find how to use linq queries in the below reference link. However, few features are not supported such as: groupby, union, intersect, distinct,except,  select, selectmany, join, group join, concat, skipwhile, take, skip and takewhile.  

    Note: Opening the realm instance asynchronously for the first time is recommended. Once the data is synchronized, the instance should be called synchronously.  

    You can also download realm studio, create a realm file, and add the data. This helps to minimize the code in your application.   

    Below are a few reference links that might help with further information 

    1. Using realm with xamarin
    2. Linq support
    3. Realm Encryption
    Profile

    Mounika Rajapuram

    Module Lead

    Mounika calls herself a dynamic professional with expertise in developing mobile applications for iOS and Android. With C# and Xamarin as primary areas of expertise, she also likes to dwell in doodle art in her pastime.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon