Xamarin.Forms - Working With Realm Database

Introduction
 
The Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files are the most easily done tasks using native file APIs on each platform. Alternatively, embedded resources are also a simpler solution to distribute the data files with an app.
 
 
Realm

Realm is a database built from the ground up to cop up the unique challenges of mobile app development, that runs directly inside phones, tablets, or wearables.
 
Realm.Xamarin is built specifically with Xamarin developers in mind and is designed from the ground up for reactive app development. Data binding allows you to connect your UI to your persisted data in a very smooth and seamless way. It’s not only easy to use, but also heavily optimized for performance, which allows you to make apps that are more responsive and consume less power and memory.

Why use Realm
  1. It is fast
  2. It is cross-platform
  3. It is strongly supported by the community
  4. It is easy to use
Prerequisites
  • Visual Studio 2017 (Windows or Mac)
Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.

Choose the Cross-platform App project under Visual C#-->Cross-platform in the New Project dialog.
 
 

Now, select a Blank App and choose Portable Class Library (PCL).

 
 
Subsequently, go to the solution. In there, you get all the files and sources of your project (PCL). Now, select XAML page and double-click to open the MainPage.Xaml page.

You now have a basic Xamarin.Forms app. Click the Play button to try it out.


Setting up the User Interface

Go to MainPage.Xaml and write the following code.
 
MainPage.xaml
  1. <ContentView AbsoluteLayout.LayoutFlags="All"  AbsoluteLayout.LayoutBounds="0, 0, 1, 1">  
  2.                 <StackLayout>  
  3.                     <StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="StartAndExpand">  
  4.                         <Image x:Name="imgBanner" WidthRequest="300"></Image>  
  5.                         <Entry x:Name="txtStudentName" Placeholder="Enter Name..."></Entry>  
  6.                         <Button Text="Add Student" WidthRequest="100" x:Name="btnAdd" Clicked="btnAdd_Clicked"></Button>  
  7.                         <ListView x:Name="listStudent" ItemSelected="listStudent_ItemSelected">  
  8.                             <ListView.ItemTemplate>  
  9.                                 <DataTemplate>  
  10.                                     <ViewCell>  
  11.                                         <StackLayout>  
  12.                                             <Label Text="{Binding StudentName}"></Label>  
  13.                                         </StackLayout>  
  14.                                     </ViewCell>  
  15.                                 </DataTemplate>  
  16.                             </ListView.ItemTemplate>  
  17.                         </ListView>  
  18.                     </StackLayout>  
  19.                 </StackLayout>  
  20.             </ContentView> 
Click the Play button to try it out.

 
 
Add Realm
 
In this step, add Realm database to your project. You can install Realm via NuGet, or you can browse the source code on GitHub.

Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search "Realm" and add Package. Remember to install it for each project (PCL, Android, iO, and UWP).

 
Note
For UWP, .NET Core, and other .NET Standard projects - due to changes in NuGet 3.1, packages are no longer able to create content files. So, the FodyWeavers.xml file will not be created automatically. You’ll need to manually create the file and paste the content below (PCL, Android, iOS, UWP).

FodyWeavers.xml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <Weavers>  
  3. <RealmWeaver />  
  4. </Weavers>   
Creating Model
 
Go to Solution—>PCL—>Right click—>New—>Class—>Student.cs.
 
 
 
Now, write the following code on Student.cs.

Student.cs
  1. using Realms;  
  2. namespace XamarinFormsRelam.Models  
  3. {  
  4.     public class Student:RealmObject  
  5.     {  
  6.         [PrimaryKey]  
  7.         public int StudentID { getset; }  
  8.         public string StudentName { getset; }  
  9.     }  
  10. }  
Insert

Now, write the following code to insert data into Realm Database.

Student - Table Name
 
MainPage.xaml.cs
  1. private void btnAdd_Clicked(object sender, EventArgs e)  
  2.        {  
  3.            var realmDB = Realm.GetInstance();  
  4.            var students= realmDB.All<Student>().ToList();  
  5.            var maxStudentId = 0;  
  6.            if (students.Count!=0)  
  7.            {  
  8.   
  9.                 maxStudentId = students.Max(s=>s.StudentID);  
  10.            }  
  11.            Student student = new Student()  
  12.            {  
  13.                StudentID = maxStudentId + 1,  
  14.                StudentName = txtStudentName.Text  
  15.            };  
  16.            realmDB.Write(() =>  
  17.            {  
  18.                realmDB.Add(student);  
  19.            });  
  20.            txtStudentName.Text = string.Empty;  
  21.            List<Student> studentList = realmDB.All<Student>().ToList();  
  22.            listStudent.ItemsSource = studentList;  
  23.   
  24.        } 
Click the Play button to try it out.

 

Read

Now, write the following code to read all data from Realm Database.
 
MainPage.xaml.cs
  1. List<Student> studentList = realmDB.All<Student>().ToList();  
  2. listStudent.ItemsSource = studentList;  
Update

Setting up the User Interface for Update

Go to MainPage.Xaml and write the following code.

MainPage.xaml
  1. <StackLayout VerticalOptions="Center" HorizontalOptions="Center">  
  2.                     <StackLayout Orientation="Vertical" HeightRequest="200" WidthRequest="300" BackgroundColor="White">  
  3.                         <Entry Margin="20,20,20,10" x:Name="txtEditStudentName" Placeholder="Edit Studentname"></Entry>  
  4.                         <Button Margin="20,0,20,0" Text="Edit" Clicked="Button_Clicked_1"></Button>  
  5.                         <Button Margin="20,0,20,0" Text="Cancel" Clicked="Button_Clicked"></Button>  
  6.                     </StackLayout>  
  7.                 </StackLayout> 
Now, write the following code to update data to Realm Database.

MainPage.xaml.cs
  1. private async void Button_Clicked_1(object sender, EventArgs e)  
  2.         {  
  3.             var realmDB = Realm.GetInstance();  
  4.             var selectedStudent = realmDB.All<Student>().First(b => b.StudentID == editStudent.StudentID);  
  5.             using (var db = realmDB.BeginWrite())  
  6.             {  
  7.                 editStudent.StudentName = txtEditStudentName.Text;  
  8.                 db.Commit();  
  9.             }  
  10.             await DisplayAlert("Success""Student Updated","OK");  
  11.             txtEditStudentName.Text = string.Empty;  
  12.             popupEditView.IsVisible = false;  
  13.   
  14.         }  
Click the Play button to try it out.
 
 
 
 

Delete

Now, write the following code to delete data from Realm Database.

MainPage.xaml.cs
  1. var removeStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);  
  2.                         using (var db = realmDB.BeginWrite())  
  3.                         {  
  4.                             realmDB.Remove(removeStudent);  
  5.                             db.Commit();  
  6.                         }  
  7.                         await DisplayAlert("Success""Student Deleted""OK");  
  8.                         popupOptionView.IsVisible = false;  
  9.                         List<Student> studentList = realmDB.All<Student>().ToList();  
  10.                         listStudent.ItemsSource = studentList;  
Click the Play button to try it out.

 
 
 
 
Full Code - MainPage.Xaml.cs

MainPage.Xaml.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Xamarin.Forms;  
  7. using XamarinFormsRelam.Models;  
  8. using Realms;  
  9. namespace XamarinFormsRelam  
  10. {  
  11.     public partial class MainPage : ContentPage  
  12.     {  
  13.         List<OptionItems> optionItems = new List<OptionItems>();  
  14.         Student editStudent;  
  15.         public MainPage()  
  16.         {  
  17.             InitializeComponent();  
  18.             imgBanner.Source = ImageSource.FromResource("XamarinFormsRelam.images.banner.png");  
  19.             var realmDB = Realm.GetInstance();  
  20.   
  21.             List<Student> studentList = realmDB.All<Student>().ToList();  
  22.             listStudent.ItemsSource=studentList;  
  23.         }  
  24.   
  25.         private void btnAdd_Clicked(object sender, EventArgs e)  
  26.         {  
  27.             var realmDB = Realm.GetInstance();  
  28.             var students= realmDB.All<Student>().ToList();  
  29.             var maxStudentId = 0;  
  30.             if (students.Count!=0)  
  31.             {  
  32.   
  33.                  maxStudentId = students.Max(s=>s.StudentID);  
  34.             }  
  35.             Student student = new Student()  
  36.             {  
  37.                 StudentID = maxStudentId + 1,  
  38.                 StudentName = txtStudentName.Text  
  39.             };  
  40.             realmDB.Write(() =>  
  41.             {  
  42.                 realmDB.Add(student);  
  43.             });  
  44.             txtStudentName.Text = string.Empty;  
  45.             List<Student> studentList = realmDB.All<Student>().ToList();  
  46.             listStudent.ItemsSource = studentList;  
  47.   
  48.         }  
  49.         private async void listOptions_ItemSelected(object sender, SelectedItemChangedEventArgs e)  
  50.         {  
  51.             var realmDB = Realm.GetInstance();  
  52.             OptionItems selectedItem = optionList.SelectedItem as OptionItems;  
  53.             if (selectedItem != null)  
  54.             {  
  55.                 switch (selectedItem.OptionText)  
  56.                 {  
  57.   
  58.                     case "Edit":  
  59.                         popupOptionView.IsVisible = false;  
  60.                         popupEditView.IsVisible = true;  
  61.                         editStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);  
  62.                         txtEditStudentName.Text = editStudent.StudentName;  
  63.                         break;  
  64.   
  65.                     case "Delete":  
  66.                         var removeStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);  
  67.                         using (var db = realmDB.BeginWrite())  
  68.                         {  
  69.                             realmDB.Remove(removeStudent);  
  70.                             db.Commit();  
  71.                         }  
  72.                         await DisplayAlert("Success""Student Deleted""OK");  
  73.                         popupOptionView.IsVisible = false;  
  74.                         List<Student> studentList = realmDB.All<Student>().ToList();  
  75.                         listStudent.ItemsSource = studentList;  
  76.                         break;  
  77.   
  78.                     default:  
  79.                         popupOptionView.IsVisible = false;  
  80.                         break;  
  81.                 }  
  82.   
  83.                 optionList.SelectedItem = null;  
  84.             }  
  85.   
  86.         }  
  87.         protected override void OnAppearing()  
  88.         {  
  89.             base.OnAppearing();  
  90.             var realmDb = Realm.GetInstance();  
  91.         }  
  92.   
  93.         private void listStudent_ItemSelected(object sender, SelectedItemChangedEventArgs e)  
  94.         {  
  95.             Student selectedStudent = listStudent.SelectedItem as Student;  
  96.               
  97.             if(selectedStudent!=null)  
  98.             {  
  99.                 optionItems.Add(new OptionItems { OptionText = "Edit",StudentId=selectedStudent.StudentID});  
  100.                 optionItems.Add(new OptionItems { OptionText = "Delete", StudentId = selectedStudent.StudentID });  
  101.                 optionItems.Add(new OptionItems { OptionText = "Cancel"});  
  102.                 optionList.ItemsSource = optionItems;  
  103.                 popupOptionView.IsVisible = true;  
  104.             }  
  105.               
  106.         }  
  107.   
  108.         private void Button_Clicked(object sender, EventArgs e)  
  109.         {  
  110.             popupEditView.IsVisible = false;  
  111.         }  
  112.   
  113.         private async void Button_Clicked_1(object sender, EventArgs e)  
  114.         {  
  115.             var realmDB = Realm.GetInstance();  
  116.             var selectedStudent = realmDB.All<Student>().First(b => b.StudentID == editStudent.StudentID);  
  117.             using (var db = realmDB.BeginWrite())  
  118.             {  
  119.                 editStudent.StudentName = txtEditStudentName.Text;  
  120.                 db.Commit();  
  121.             }  
  122.             await DisplayAlert("Success""Student Updated","OK");  
  123.             txtEditStudentName.Text = string.Empty;  
  124.             popupEditView.IsVisible = false;  
  125.   
  126.         }  
  127.     }  
  128. }  
Click the Play button to try it out.

 
 
I hope you have understood how to use Realm Database in Xamarin.Forms.
 
 
Thanks for reading. Please share comments and feedback.


Similar Articles