Realm Mobile Database With Xamarin.Forms Step By Step Guide

Whenever we talk about offline data persistence in Mobile application using a database, the only database that comes into our mind is SQLite, as it is the most popular one and also the free one,  however there are many issues with it - data encryption not supported by default being the biggest one. Last year, I came to know about this new Mobile database called Realm Mobile Database which supports encryption out of the box along with many other features and after that, there was no looking back. I used it in many of my applications.

This article will be a step by step guide on how to use a Realm Mobile database with a Xamarin.Forms application. We will be using the database to persist employee data, Just like my SQLite Step By Step article. So, let’s get started.

Step 1

Create a new Xamarin.Forms app in Visual Studio Mac/Windows and add the NuGet Package of Realm Mobile Database like in the following image.

Visual Studio

Note - Realm works on PCL bait’n’switch pattern, because of which we have another benefit over SQLite , that is, we don’t need to write platform specific code to load Realm database file. It’s automatically handled by the Realm NuGet Code and we have to just care about using it in our shared code base.

Step 2

Create the Plain Old CLR Object (POCO) class for the table(s) present in the database and extend it from RealmObject class in order to use it further.

  1. using Realms;  
  2.    
  3. namespace RealmMobEx  
  4. {  
  5.     public class Employee : RealmObject  
  6.     {  
  7.         [PrimaryKey]  
  8.         public long EmpId  
  9.         { get; set; }  
  10.         public string EmpName  
  11.         { get; set; }  
  12.         public string Company  
  13.         { get; set; }  
  14.         public string Designation  
  15.         { get; set; }  
  16.         public string Department  
  17.         { get; set; }  
  18.         public string Qualification  
  19.         { get; set; }  
  20.     }  
  21. }  

Step 3

We will be using the MainPage.Xaml of application for showing the list of employees. The UI code of the same can be taken from the Sample Github Repository’s MainPage.xaml.

Step 4

Add the following code to the code behind of MainPage.Xaml.

  1. using Realms;  
  2. using System;  
  3. using System.Collections.ObjectModel;  
  4. using Xamarin.Forms;  
  5.    
  6. namespace RealmMobEx  
  7. {  
  8.     public partial class MainPage : ContentPage  
  9.     {          
  10.         public MainPage()  
  11.         {  
  12.             InitializeComponent();  
  13.               
  14.         }  
  15.    
  16.         protected override void OnAppearing()  
  17.         {  
  18.             base.OnAppearing();  
  19.             var vRealmDb = Realm.GetInstance();  
  20.             var vAllEmployees = vRealmDb.All<Employee>();  
  21.             lstData.ItemsSource = vAllEmployees;  
  22.         }  
  23.    
  24.         void OnSelection(object sender, SelectedItemChangedEventArgs e)  
  25.         {  
  26.             if (e.SelectedItem == null)  
  27.             {  
  28.                 return;  
  29.                 //ItemSelected is called on deselection,   
  30.                 //which results in SelectedItem being set to null  
  31.             }  
  32.             var vSelUser = (Employee)e.SelectedItem;  
  33.             Navigation.PushAsync(new ShowEmp(vSelUser));  
  34.         }  
  35.         public void OnNewClicked(object sender, EventArgs args)  
  36.         {  
  37.             Navigation.PushAsync(new AddEmp());  
  38.         }  
  39.     }  
  40. }  

Realm saves the data as the objects which are available in static Realm object for manipulation. As seen in the OnAppearing event handler of the above code, we are using Realm object to get the instance of database and then calling All Method to load all the Employee objects available in the database.

OnSelection and OnNewClicked are the event handlers for listView’s ItemSelected and button’s Click events respectively.

Step 5

Add a new ContentPage named AddEmp.Xaml for adding the details of new employee. The UI code of the same can be taken from the Sample Github Repository’s AddEmp.xaml.

Step 6

Add the following code to the code behind of AddEmp.Xaml.

  1. using Realms;  
  2. using System;  
  3. using System.Linq;  
  4. using Xamarin.Forms;  
  5. using Xamarin.Forms.Xaml;  
  6.    
  7. namespace RealmMobEx  
  8. {  
  9.     [XamlCompilation(XamlCompilationOptions.Compile)]  
  10.     public partial class AddEmp : ContentPage  
  11.     {  
  12.         public AddEmp()  
  13.         {  
  14.             InitializeComponent();  
  15.         }  
  16.         public void OnSaveClicked(object sender, EventArgs args)  
  17.         {  
  18.             var vRealmDb = Realm.GetInstance();  
  19.             var vEmpId = vRealmDb.All<Employee>().Count() + 1;  
  20.             var vEmployee = new Employee()  
  21.             {  
  22.                 EmpId = vEmpId,  
  23.                 EmpName = txtEmpName.Text,  
  24.                 Department = txtDepartment.Text,  
  25.                 Designation = txtDesign.Text,  
  26.                 Qualification = txtQualification.Text  
  27.             };  
  28.             vRealmDb.Write(() => {  
  29.                 vEmployee = vRealmDb.Add(vEmployee);  
  30.             });             
  31.             Navigation.PopAsync();  
  32.         }  
  33.     }  
  34. }  

In OnSaveClicked event handler of above code, we are writing the code to save the entered data in database. Just like MainPage.xaml.cs code, we are first taking the instance of the Realm database from static Realm object and then adding the values entered by user by using Write method of the vRealmDb object.

Step 7

Add a new ContentPage named ShowEmp.xaml for showing the details of selected employee on tapping/clicking on Employee list of MainPage. The UI code of the same can be taken from the Sample Github Repository’s ShowEmp.xaml.

Step 8

Add the following code to the code behind of this page.

  1. using Realms;  
  2. using System;  
  3. using System.Linq;  
  4. using Xamarin.Forms;  
  5. using Xamarin.Forms.Xaml;  
  6.    
  7. namespace RealmMobEx  
  8. {  
  9.     [XamlCompilation(XamlCompilationOptions.Compile)]  
  10.     public partial class ShowEmp : ContentPage  
  11.     {  
  12.         Employee mSelEmployee;  
  13.         public ShowEmp()  
  14.         {  
  15.             InitializeComponent();  
  16.         }  
  17.         public ShowEmp(Employee aSelEmp)  
  18.         {  
  19.             InitializeComponent();  
  20.             mSelEmployee = aSelEmp;  
  21.             BindingContext = mSelEmployee;  
  22.         }   
  23.      
  24.         public void OnEditClicked(object sender, EventArgs args)  
  25.         {  
  26.             Navigation.PushAsync(new EditEmp(mSelEmployee));  
  27.         }  
  28.         public async void OnDeleteClicked(object sender, EventArgs args)  
  29.         {  
  30.             bool accepted = await DisplayAlert("Confirm""Are you Sure ?""Yes""No");  
  31.             if (accepted)  
  32.             {  
  33.                 var vRealmDb = Realm.GetInstance();  
  34.                 var vSelEmp = vRealmDb.All<Employee>().First(b => b.EmpId == mSelEmployee.EmpId);  
  35.    
  36.                 // Delete an object with a transaction  
  37.                 using (var trans = vRealmDb.BeginWrite())  
  38.                 {  
  39.                     vRealmDb.Remove(vSelEmp);  
  40.                     trans.Commit();  
  41.                 }  
  42.             }  
  43.             await Navigation.PopToRootAsync();  
  44.         }  
  45.     }  
  46. }  

The OnDeleteClicked event handler of above code shows how we can delete the selected record from database.

Step 9

Add a new ContentPage named EditEmp.xaml for editing the details of selected employee on tapping/clicking on Employee list of MainPage. The UI code of the same can be taken from the Sample Github Repository’s EditEmp.xaml.

Step 10

Add the following code to the code behind of this page.

  1. using Realms;  
  2. using System;  
  3. using Xamarin.Forms;  
  4. using Xamarin.Forms.Xaml;  
  5.    
  6. namespace RealmMobEx  
  7. {  
  8.     [XamlCompilation(XamlCompilationOptions.Compile)]  
  9.     public partial class EditEmp : ContentPage  
  10.     {  
  11.         private Employee mSelEmployee;  
  12.    
  13.         public EditEmp(Employee mSelEmployee)  
  14.         {  
  15.             InitializeComponent();  
  16.             this.mSelEmployee = mSelEmployee;  
  17.             BindingContext = mSelEmployee;  
  18.         }  
  19.    
  20.         public void OnSaveClicked(object sender, EventArgs args)  
  21.         {  
  22.             var vRealmDb = Realm.GetInstance();  
  23.             using (var trans = vRealmDb.BeginWrite())  
  24.             {  
  25.                 mSelEmployee.EmpName = txtEmpName.Text;  
  26.                 mSelEmployee.Department = txtDepartment.Text;  
  27.                 mSelEmployee.Designation = txtDesign.Text;  
  28.                 mSelEmployee.Qualification = txtQualification.Text;                  
  29.                 trans.Commit();  
  30.             }           
  31.             Navigation.PopToRootAsync();  
  32.         }  
  33.     }  
  34. }  

The OnSaveClicked event handler of above code shows how we can edit the selected record from database.

This is how the application looks on iOS Simulator.

Visual Studio

The complete code of this article can be found at GitHub. You can use the links given in the Reference to learn more about Realm Mobile Database it’s used etc. Let me know if I have missed anything or you have any suggestions.

Happy Coding !!!

References