Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Xamarin.Forms — Working With Realm Database

DZone's Guide to

Xamarin.Forms — Working With Realm Database

Learn how to take advantage of Realm Database for mobile development when building apps with Xamarin.Forms.

· Mobile Zone ·
Free Resource

Introduction

Image title

Download the source code from the GitHub Repository.

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

Image title

Realm is a database built from the ground up for 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.

Image title

Now Select the 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

<ContentView AbsoluteLayout.LayoutFlags="All"  AbsoluteLayout.LayoutBounds="0, 0, 1, 1">
                <StackLayout>
                    <StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="StartAndExpand">
                        <Image x:Name="imgBanner" WidthRequest="300"></Image>
                        <Entry x:Name="txtStudentName" Placeholder="Enter Name..."></Entry>
                        <Button Text="Add Student" WidthRequest="100" x:Name="btnAdd" Clicked="btnAdd_Clicked"></Button>
                        <ListView x:Name="listStudent" ItemSelected="listStudent_ItemSelected">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <ViewCell>
                                        <StackLayout>
                                            <Label Text="{Binding StudentName}"></Label>
                                        </StackLayout>
                                    </ViewCell>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </ListView>
                    </StackLayout>
                </StackLayout>
            </ContentView>


Click the Play button to try it out.

Image title

Add Realm

In this step add realm database to your project

You 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."

Image title

Search "Realm" and add Package. Remember to install it to each project (PCL, Android, iOS 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 FodyWeavers.xml will not be created automatically. You’ll need to manually create the file and paste the content below(PCL, Android, iOS, UWP)

FodyWeavers.xml

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

Creating Model

Go to Solution—>PCL—>Right click—>New—>Class—>Student.cs.

Now, write the following code on Student.cs

Student.cs

using Realms;
namespace XamarinFormsRelam.Models
{
    public class Student:RealmObject
    {
        [PrimaryKey]
        public int StudentID { get; set; }
        public string StudentName { get; set; }
    }
}

Insert

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

Student — Table Name

MainPage.xaml.cs

private void btnAdd_Clicked(object sender, EventArgs e)
        {
            var realmDB = Realm.GetInstance();
            var students= realmDB.All<Student>().ToList();
            var maxStudentId = 0;
            if (students.Count!=0)
            {

                 maxStudentId = students.Max(s=>s.StudentID);
            }
            Student student = new Student()
            {
                StudentID = maxStudentId + 1,
                StudentName = txtStudentName.Text
            };
            realmDB.Write(() =>
            {
                realmDB.Add(student);
            });
            txtStudentName.Text = string.Empty;
            List<Student> studentList = realmDB.All<Student>().ToList();
            listStudent.ItemsSource = studentList;

        }


Click the Play button to try it out.

Image title

Read

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

MainPage.xaml.cs

 List<Student> studentList = realmDB.All<Student>().ToList();
 listStudent.ItemsSource = studentList;


Update

Setting up the User Interface for Update

Go to MainPage.Xaml and write the following code.

MainPage.xaml

<StackLayout VerticalOptions="Center" HorizontalOptions="Center">
                    <StackLayout Orientation="Vertical" HeightRequest="200" WidthRequest="300" BackgroundColor="White">
                        <Entry Margin="20,20,20,10" x:Name="txtEditStudentName" Placeholder="Edit Studentname"></Entry>
                        <Button Margin="20,0,20,0" Text="Edit" Clicked="Button_Clicked_1"></Button>
                        <Button Margin="20,0,20,0" Text="Cancel" Clicked="Button_Clicked"></Button>
                    </StackLayout>
                </StackLayout>

Now, write the following code to update data to Realm Database.

MainPage.xaml.cs

private async void Button_Clicked_1(object sender, EventArgs e)
        {
            var realmDB = Realm.GetInstance();
            var selectedStudent = realmDB.All<Student>().First(b => b.StudentID == editStudent.StudentID);
            using (var db = realmDB.BeginWrite())
            {
                editStudent.StudentName = txtEditStudentName.Text;
                db.Commit();
            }
            await DisplayAlert("Success", "Student Updated","OK");
            txtEditStudentName.Text = string.Empty;
            popupEditView.IsVisible = false;

Click the Play button to try it out.

Image title

Image title

Delete

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

MainPage.xaml.cs

var removeStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);
                        using (var db = realmDB.BeginWrite())
                        {
                            realmDB.Remove(removeStudent);
                            db.Commit();
                        }
                        await DisplayAlert("Success", "Student Deleted", "OK");
                        popupOptionView.IsVisible = false;
                        List<Student> studentList = realmDB.All<Student>().ToList();
                        listStudent.ItemsSource = studentList;

Click the Play button to try it out.

Image title

Image title

Full Code — MainPage.Xaml.cs

MainPage.Xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using XamarinFormsRelam.Models;
using Realms;
namespace XamarinFormsRelam
{
    public partial class MainPage : ContentPage
    {
        List<OptionItems> optionItems = new List<OptionItems>();
        Student editStudent;
        public MainPage()
        {
            InitializeComponent();
            imgBanner.Source = ImageSource.FromResource("XamarinFormsRelam.images.banner.png");
            var realmDB = Realm.GetInstance();

            List<Student> studentList = realmDB.All<Student>().ToList();
            listStudent.ItemsSource=studentList;
        }

        private void btnAdd_Clicked(object sender, EventArgs e)
        {
            var realmDB = Realm.GetInstance();
            var students= realmDB.All<Student>().ToList();
            var maxStudentId = 0;
            if (students.Count!=0)
            {

                 maxStudentId = students.Max(s=>s.StudentID);
            }
            Student student = new Student()
            {
                StudentID = maxStudentId + 1,
                StudentName = txtStudentName.Text
            };
            realmDB.Write(() =>
            {
                realmDB.Add(student);
            });
            txtStudentName.Text = string.Empty;
            List<Student> studentList = realmDB.All<Student>().ToList();
            listStudent.ItemsSource = studentList;

        }
        private async void listOptions_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var realmDB = Realm.GetInstance();
            OptionItems selectedItem = optionList.SelectedItem as OptionItems;
            if (selectedItem != null)
            {
                switch (selectedItem.OptionText)
                {

                    case "Edit":
                        popupOptionView.IsVisible = false;
                        popupEditView.IsVisible = true;
                        editStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);
                        txtEditStudentName.Text = editStudent.StudentName;
                        break;

                    case "Delete":
                        var removeStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);
                        using (var db = realmDB.BeginWrite())
                        {
                            realmDB.Remove(removeStudent);
                            db.Commit();
                        }
                        await DisplayAlert("Success", "Student Deleted", "OK");
                        popupOptionView.IsVisible = false;
                        List<Student> studentList = realmDB.All<Student>().ToList();
                        listStudent.ItemsSource = studentList;
                        break;

                    default:
                        popupOptionView.IsVisible = false;
                        break;
                }

                optionList.SelectedItem = null;
            }

        }
        protected override void OnAppearing()
        {
            base.OnAppearing();
            var realmDb = Realm.GetInstance();
        }

        private void listStudent_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            Student selectedStudent = listStudent.SelectedItem as Student;

            if(selectedStudent!=null)
            {
                optionItems.Add(new OptionItems { OptionText = "Edit",StudentId=selectedStudent.StudentID});
                optionItems.Add(new OptionItems { OptionText = "Delete", StudentId = selectedStudent.StudentID });
                optionItems.Add(new OptionItems { OptionText = "Cancel"});
                optionList.ItemsSource = optionItems;
                popupOptionView.IsVisible = true;
            }

        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            popupEditView.IsVisible = false;
        }

        private async void Button_Clicked_1(object sender, EventArgs e)
        {
            var realmDB = Realm.GetInstance();
            var selectedStudent = realmDB.All<Student>().First(b => b.StudentID == editStudent.StudentID);
            using (var db = realmDB.BeginWrite())
            {
                editStudent.StudentName = txtEditStudentName.Text;
                db.Commit();
            }
            await DisplayAlert("Success", "Student Updated","OK");
            txtEditStudentName.Text = string.Empty;
            popupEditView.IsVisible = false;

        }
    }
}

Click the Play button to try it out.

Image title

I hope you have understood how to use  Realm Database in Xamarin.Forms.

Thanks for reading. Please share comments and feedback.

Download the source code from the GitHub Repository.

Topics:
xamarin ,cross platform development ,mobile ,mobile app development ,xamarin.forms ,tutorial ,android

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}