Whenever we talk about offline data persistence in Mobile application using a database the only database comes in 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 one the biggest one. Last year I came to know about this new Mobile database called Realm Mobile Database which supports encryption out of 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 an 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 following image:
Note: Realm works on PCL bait’n’switch pattern, because of which we have another benefit over SQLite is that, we don’t need to write platform specific code the load Realm database file it’s being 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 used it further.
using Realms;
namespace RealmMobEx
{
public class Employee : RealmObject
{
[PrimaryKey]
public long EmpId
{ get; set; }
public string EmpName
{ get; set; }
public string Company
{ get; set; }
public string Designation
{ get; set; }
public string Department
{ get; set; }
public string Qualification
{ get; set; }
}
}
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:
using Realms;
using System;
using System.Collections.ObjectModel;
using Xamarin.Forms;
namespace RealmMobEx
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
var vRealmDb = Realm.GetInstance();
var vAllEmployees = vRealmDb.All<Employee>();
lstData.ItemsSource = vAllEmployees;
}
void OnSelection(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
{
return;
}
var vSelUser = (Employee)e.SelectedItem;
Navigation.PushAsync(new ShowEmp(vSelUser));
}
public void OnNewClicked(object sender, EventArgs args)
{
Navigation.PushAsync(new AddEmp());
}
}
}
Realm save 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:
using Realms;
using System;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace RealmMobEx
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class AddEmp : ContentPage
{
public AddEmp()
{
InitializeComponent();
}
public void OnSaveClicked(object sender, EventArgs args)
{
var vRealmDb = Realm.GetInstance();
var vEmpId = vRealmDb.All<Employee>().Count() + 1;
var vEmployee = new Employee()
{
EmpId = vEmpId,
EmpName = txtEmpName.Text,
Department = txtDepartment.Text,
Designation = txtDesign.Text,
Qualification = txtQualification.Text
};
vRealmDb.Write(() => {
vEmployee = vRealmDb.Add(vEmployee);
});
Navigation.PopAsync();
}
}
}
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 :
using Realms;
using System;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace RealmMobEx
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ShowEmp : ContentPage
{
Employee mSelEmployee;
public ShowEmp()
{
InitializeComponent();
}
public ShowEmp(Employee aSelEmp)
{
InitializeComponent();
mSelEmployee = aSelEmp;
BindingContext = mSelEmployee;
}
public void OnEditClicked(object sender, EventArgs args)
{
Navigation.PushAsync(new EditEmp(mSelEmployee));
}
public async void OnDeleteClicked(object sender, EventArgs args)
{
bool accepted = await DisplayAlert("Confirm", "Are you Sure ?", "Yes", "No");
if (accepted)
{
var vRealmDb = Realm.GetInstance();
var vSelEmp = vRealmDb.All<Employee>().First(b => b.EmpId == mSelEmployee.EmpId);
using (var trans = vRealmDb.BeginWrite())
{
vRealmDb.Remove(vSelEmp);
trans.Commit();
}
}
await Navigation.PopToRootAsync();
}
}
}
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 :
using Realms;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace RealmMobEx
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class EditEmp : ContentPage
{
private Employee mSelEmployee;
public EditEmp(Employee mSelEmployee)
{
InitializeComponent();
this.mSelEmployee = mSelEmployee;
BindingContext = mSelEmployee;
}
public void OnSaveClicked(object sender, EventArgs args)
{
var vRealmDb = Realm.GetInstance();
using (var trans = vRealmDb.BeginWrite())
{
mSelEmployee.EmpName = txtEmpName.Text;
mSelEmployee.Department = txtDepartment.Text;
mSelEmployee.Designation = txtDesign.Text;
mSelEmployee.Qualification = txtQualification.Text;
trans.Commit();
}
Navigation.PopToRootAsync();
}
}
}
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:
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 uses etc. Let me know if I has missed anything or have any suggestions.
Happy Coding
References :