Xamarin.Forms - Working With Firebase Realtime Database CRUD Operations

In this article, you will learn how to use Firebase Realtime Database with CRUD Operations in Xamarin.Forms.

Introduction
 
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations
 
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.
 
Firebase
 
Firebase gives you functionality like analytics, databases, messaging and crash reporting so you can move quickly and focus on your users.
 Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations
Firebase is a back-end platform for building Web, Android, and iOS applications. It offers real-time database, different APIs, multiple authentication types and hosting platform. This is an introductory tutorial, which covers the basics of the Firebase platform and explains how to deal with its various components and sub-components.
 
Build apps with Firebase
  • Real-time Database
  • Storage
  • Notifications
  • Authentication
  • Hosting
Prerequisites
  • Visual Studio 2017 or Later(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 or download the source from the following GitHub link -
 
 
Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or, open a project or solution for your computer.
 
Now, you need to click "Create a new project".
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Now, filter by Project Type: Mobile.
 
Choose the Mobile App (Xamarin. forms) project under C# and Mobile.
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
Now, select the blank app and target platforms - Android, iOS and Windows (UWP).
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). 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.
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Create a project in Firebase
 
In this step, create a project in Firebase. Go to the following link.
 
 
Click "Add Project".
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Now, give the project a name and select your country. Then, read the terms. Afterward, click "Create project".
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Now, your project is ready, click "Continue".
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
In this step, choose Database under the Project Overview. Now, click "Create database".
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
In this step, write the read and write rules.
  1. {  
  2.   /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */  
  3.   "rules": {  
  4.     ".read""auth==null",  
  5.     ".write":"auth==null"  
  6.   }  
  7. }  
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations
 
Now, your Firebase Realtime Database is ready. You can use your database API URI here.
 
 Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations
 
Setting up the User Interface
 
Go to MainPage.Xaml and write the following code.
 
MainPage.xaml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:XamarinFirebase"  
  5.              x:Class="XamarinFirebase.MainPage">  
  6.   
  7.     <StackLayout>  
  8.         <StackLayout>  
  9.             <StackLayout HorizontalOptions="Center" VerticalOptions="Start">  
  10.                 <Image x:Name="imgBanner" Source="banner.png" ></Image>  
  11.                 <Image Margin="0,0,0,10" HeightRequest="100" Source="firebase.png" ></Image>  
  12.                 <Label Margin="0,0,0,10" Text="Firebase Realtime Database" FontAttributes="Bold" FontSize="Large" TextColor="Gray" HorizontalTextAlignment="Center" ></Label>  
  13.                 <Entry x:Name="txtId" Placeholder="ID"></Entry>  
  14.                 <Entry x:Name="txtName" Placeholder="Enter Name"></Entry>  
  15.                 <StackLayout  HorizontalOptions="CenterAndExpand" Orientation="Horizontal">  
  16.                     <Button x:Name="btnAdd" WidthRequest="200" Text="Add" Clicked="BtnAdd_Clicked"/>  
  17.                     <Button x:Name="btnRetrive" WidthRequest="200" Text="Retrive" Clicked="BtnRetrive_Clicked"/>  
  18.                 </StackLayout>  
  19.                 <StackLayout HorizontalOptions="CenterAndExpand" Orientation="Horizontal">  
  20.                     <Button x:Name="btnUpdate" WidthRequest="200" Text="Update" Clicked="BtnUpdate_Clicked" />  
  21.                     <Button x:Name="btnDelete" WidthRequest="200" Text="Delete" Clicked="BtnDelete_Clicked" />  
  22.                 </StackLayout>  
  23.                   
  24.                 <ListView x:Name="lstPersons">  
  25.                     <ListView.ItemTemplate>  
  26.                         <DataTemplate>  
  27.                             <TextCell Text="{Binding Name}"></TextCell>  
  28.                         </DataTemplate>  
  29.                     </ListView.ItemTemplate>  
  30.                 </ListView>  
  31.             </StackLayout>  
  32.         </StackLayout>  
  33.     </StackLayout>  
  34.   
  35. </ContentPage>  
Click the "Play" button to try it out.
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
NuGet Packages
 
Now, add the following NuGet packages.
  1. FirebaseDatabase.net
Add FirebaseDatabase.net NuGet
 
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search for "FirebaseDatabase.net" and add Package. Remember to install it for each project (.NET Standard, Android, iOS, and UWP).
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 

Create a Model
 
In this step, you can create a model for deserializing your response.
 
Person.cs
  1. namespace XamarinFirebase.Model  
  2. {  
  3.     public class Person  
  4.     {  
  5.         public int PersonId { getset; }  
  6.         public string Name { getset; }  
  7.     }  
  8. }  
Connect Firebase
 
Now, write the following code to connect to your Firebase Realtime Database.
  1. using Firebase.Database;  
  2. using Firebase.Database.Query;  
  3.   
  4. FirebaseClient firebase = new FirebaseClient("https://xamarinfirebase-xxxxx.firebaseio.com/");  
  5.    
Read All
 
Now, write the code to read all data from Firebase Realtime Database.
 
FirebaseHelper.cs
  1. public async Task<List<Person>> GetAllPersons()  
  2.         {  
  3.   
  4.             return (await firebase  
  5.               .Child("Persons")  
  6.               .OnceAsync<Person>()).Select(item => new Person  
  7.               {  
  8.                   Name = item.Object.Name,  
  9.                   PersonId = item.Object.PersonId  
  10.               }).ToList();  
  11.         }  
MainPage.Xaml.cs
  1. FirebaseHelper firebaseHelper = new FirebaseHelper();  
  2.         public MainPage()  
  3.         {  
  4.             InitializeComponent();  
  5.         }  
  6.   
  7.         protected async override void OnAppearing()  
  8.         {  
  9.   
  10.             base.OnAppearing();  
  11.             var allPersons = await firebaseHelper.GetAllPersons();  
  12.             lstPersons.ItemsSource = allPersons;  
  13.         }  
Click the "Play" button to try it out.
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Insert
 
Now, write the following code to insert data into Firebase Realtime Database.
  1. public async Task AddPerson(int personId,string name)  
  2.         {  
  3.   
  4.             await firebase  
  5.               .Child("Persons")  
  6.               .PostAsync(new Person() { PersonId=personId, Name = name });  
  7.         }  
  8.   
  9. private async void BtnAdd_Clicked(object sender, EventArgs e)  
  10.         {  
  11.             await firebaseHelper.AddPerson(Convert.ToInt32(txtId.Text), txtName.Text);  
  12.             txtId.Text = string.Empty;  
  13.             txtName.Text = string.Empty;  
  14.             await DisplayAlert("Success""Person Added Successfully""OK");  
  15.             var allPersons = await firebaseHelper.GetAllPersons();  
  16.             lstPersons.ItemsSource = allPersons;  
  17.         }  
Click the "Play" button to try it out.
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Read
 
Now, write the following code to read data from Firebase Realtime Database.
  1. public async Task<Person> GetPerson(int personId)  
  2.         {  
  3.             var allPersons = await GetAllPersons();  
  4.             await firebase  
  5.               .Child("Persons")  
  6.               .OnceAsync<Person>();  
  7.             return allPersons.Where(a => a.PersonId == personId).FirstOrDefault();  
  8.         }  
  9.   
  10. private async void BtnRetrive_Clicked(object sender, EventArgs e)  
  11.         {  
  12.             var person = await firebaseHelper.GetPerson(Convert.ToInt32(txtId.Text));  
  13.             if(person!=null)  
  14.             {  
  15.                 txtId.Text = person.PersonId.ToString();  
  16.                 txtName.Text = person.Name;  
  17.                 await DisplayAlert("Success""Person Retrive Successfully""OK");  
  18.                   
  19.             }  
  20.             else  
  21.             {  
  22.                 await DisplayAlert("Success""No Person Available""OK");  
  23.             }  
  24.               
  25.         }  
Click the "Play" button to try it out.
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Update
 
Now, write the following code to update data to Firebase Realtime Database.
  1. public async Task UpdatePerson(int personId, string name)  
  2.         {  
  3.             var toUpdatePerson = (await firebase  
  4.               .Child("Persons")  
  5.               .OnceAsync<Person>()).Where(a => a.Object.PersonId == personId).FirstOrDefault();  
  6.   
  7.             await firebase  
  8.               .Child("Persons")  
  9.               .Child(toUpdatePerson.Key)  
  10.               .PutAsync(new Person() { PersonId = personId, Name = name });  
  11.         }  
  12.   
  13. private async void BtnUpdate_Clicked(object sender, EventArgs e)  
  14.         {  
  15.             await firebaseHelper.UpdatePerson(Convert.ToInt32(txtId.Text), txtName.Text);  
  16.             txtId.Text = string.Empty;  
  17.             txtName.Text = string.Empty;  
  18.             await DisplayAlert("Success""Person Updated Successfully""OK");  
  19.             var allPersons = await firebaseHelper.GetAllPersons();  
  20.             lstPersons.ItemsSource = allPersons;  
  21.         }   
Click the Play button to try it out.
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Delete
 
Now, write the following code to delete data from Firebase Realtime Database.
  1. public async Task DeletePerson(int personId)  
  2.         {  
  3.             var toDeletePerson = (await firebase  
  4.               .Child("Persons")  
  5.               .OnceAsync<Person>()).Where(a => a.Object.PersonId == personId).FirstOrDefault();  
  6.             await firebase.Child("Persons").Child(toDeletePerson.Key).DeleteAsync();  
  7.   
  8.         }  
  9.   
  10.   
  11. private async void BtnDelete_Clicked(object sender, EventArgs e)  
  12.         {  
  13.             await firebaseHelper.DeletePerson(Convert.ToInt32(txtId.Text));  
  14.             await DisplayAlert("Success""Person Deleted Successfully""OK");  
  15.             var allPersons = await firebaseHelper.GetAllPersons();  
  16.             lstPersons.ItemsSource = allPersons;  
  17.         }  
Click the Play button to try it out.
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Xamarin.Forms - Working with Firebase Realtime Database CRUD Operations 
 
Full code
 
FirebaseHelper.cs
  1. using XamarinFirebase.Model;  
  2. using Firebase.Database;  
  3. using Firebase.Database.Query;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Newtonsoft.Json;  
  7. namespace XamarinFirebase.Helper  
  8. {  
  9.       
  10.     public class FirebaseHelper  
  11.     {  
  12.         FirebaseClient firebase = new FirebaseClient("https://xamarinfirebase-909d2.firebaseio.com/");  
  13.   
  14.         public async Task<List<Person>> GetAllPersons()  
  15.         {  
  16.   
  17.             return (await firebase  
  18.               .Child("Persons")  
  19.               .OnceAsync<Person>()).Select(item => new Person  
  20.               {  
  21.                   Name = item.Object.Name,  
  22.                   PersonId = item.Object.PersonId  
  23.               }).ToList();  
  24.         }  
  25.   
  26.         public async Task AddPerson(int personId,string name)  
  27.         {  
  28.   
  29.             await firebase  
  30.               .Child("Persons")  
  31.               .PostAsync(new Person() { PersonId=personId, Name = name });  
  32.         }  
  33.   
  34.         public async Task<Person> GetPerson(int personId)  
  35.         {  
  36.             var allPersons = await GetAllPersons();  
  37.             await firebase  
  38.               .Child("Persons")  
  39.               .OnceAsync<Person>();  
  40.             return allPersons.Where(a => a.PersonId == personId).FirstOrDefault();  
  41.         }  
  42.   
  43.         public async Task UpdatePerson(int personId, string name)  
  44.         {  
  45.             var toUpdatePerson = (await firebase  
  46.               .Child("Persons")  
  47.               .OnceAsync<Person>()).Where(a => a.Object.PersonId == personId).FirstOrDefault();  
  48.   
  49.             await firebase  
  50.               .Child("Persons")  
  51.               .Child(toUpdatePerson.Key)  
  52.               .PutAsync(new Person() { PersonId = personId, Name = name });  
  53.         }  
  54.   
  55.         public async Task DeletePerson(int personId)  
  56.         {  
  57.             var toDeletePerson = (await firebase  
  58.               .Child("Persons")  
  59.               .OnceAsync<Person>()).Where(a => a.Object.PersonId == personId).FirstOrDefault();  
  60.             await firebase.Child("Persons").Child(toDeletePerson.Key).DeleteAsync();  
  61.   
  62.         }  
  63.     }  
  64.       
  65. }   
MainPage.Xaml.cs
  1. using XamarinFirebase.Helper;  
  2. using XamarinFirebase.Model;  
  3.   
  4. namespace XamarinFirebase  
  5. {  
  6.     public partial class MainPage : ContentPage  
  7.     {  
  8.         FirebaseHelper firebaseHelper = new FirebaseHelper();  
  9.         public MainPage()  
  10.         {  
  11.             InitializeComponent();  
  12.         }  
  13.   
  14.         protected async override void OnAppearing()  
  15.         {  
  16.   
  17.             base.OnAppearing();  
  18.             var allPersons = await firebaseHelper.GetAllPersons();  
  19.             lstPersons.ItemsSource = allPersons;  
  20.         }  
  21.   
  22.         private async void BtnAdd_Clicked(object sender, EventArgs e)  
  23.         {  
  24.             await firebaseHelper.AddPerson(Convert.ToInt32(txtId.Text), txtName.Text);  
  25.             txtId.Text = string.Empty;  
  26.             txtName.Text = string.Empty;  
  27.             await DisplayAlert("Success""Person Added Successfully""OK");  
  28.             var allPersons = await firebaseHelper.GetAllPersons();  
  29.             lstPersons.ItemsSource = allPersons;  
  30.         }  
  31.   
  32.         private async void BtnRetrive_Clicked(object sender, EventArgs e)  
  33.         {  
  34.             var person = await firebaseHelper.GetPerson(Convert.ToInt32(txtId.Text));  
  35.             if(person!=null)  
  36.             {  
  37.                 txtId.Text = person.PersonId.ToString();  
  38.                 txtName.Text = person.Name;  
  39.                 await DisplayAlert("Success""Person Retrive Successfully""OK");  
  40.                   
  41.             }  
  42.             else  
  43.             {  
  44.                 await DisplayAlert("Success""No Person Available""OK");  
  45.             }  
  46.               
  47.         }  
  48.   
  49.         private async void BtnUpdate_Clicked(object sender, EventArgs e)  
  50.         {  
  51.             await firebaseHelper.UpdatePerson(Convert.ToInt32(txtId.Text), txtName.Text);  
  52.             txtId.Text = string.Empty;  
  53.             txtName.Text = string.Empty;  
  54.             await DisplayAlert("Success""Person Updated Successfully""OK");  
  55.             var allPersons = await firebaseHelper.GetAllPersons();  
  56.             lstPersons.ItemsSource = allPersons;  
  57.         }  
  58.   
  59.         private async void BtnDelete_Clicked(object sender, EventArgs e)  
  60.         {  
  61.             await firebaseHelper.DeletePerson(Convert.ToInt32(txtId.Text));  
  62.             await DisplayAlert("Success""Person Deleted Successfully""OK");  
  63.             var allPersons = await firebaseHelper.GetAllPersons();  
  64.             lstPersons.ItemsSource = allPersons;  
  65.         }  
  66.     }  
  67. }   
I hope you have understood, how to use Firebase Realtime Database with CRUD Operations in Xamarin.Forms. Thanks for reading. Please share your comments and feedback.
 
Happy Coding :)