Delpin Susai Raj Thursday, 7 February 2019

Xamarin.Forms - Working with LiteDB CRUD Operations

In this blog post , you will learn how to use LiteDB Database with CRUD Operations in Xamarin.Forms.


Introduction




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.

LiteDB



  1. LiteDB is serverless database. fully written in C# code.
  2. LiteDB stores documents in the BSON (Binary JSON) data format like MongoDB.
  3. LiteDB is a simple and fast NoSQL database. use to build Mobile, Desktop and small web applications. 



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 source here

https://github.com/susairajs/XamarinForms-LiteDB

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




Now, filter by Project Type: Mobile
Choose the Mobile App (Xamarin. forms) project under C# and Mobile.

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

Now, select the blank app and target platforms - Android, iOS and Windows (UWP).
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.


Setting up the User Interface

Go to MainPage.Xaml and write the following code.

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:XamarinLiteDB"
x:Class="XamarinLiteDB.MainPage">
<StackLayout>
<StackLayout>
<StackLayout HorizontalOptions="Center" VerticalOptions="Start">
<Image x:Name="imgBanner" Source="banner.png" ></Image>
<Image Margin="0,0,0,10" HeightRequest="100" Source="liteDB.png" ></Image>
<Label Margin="0,0,0,10" Text="LiteDB" FontAttributes="Bold" FontSize="Large" TextColor="Gray" HorizontalTextAlignment="Center" ></Label>
<Entry x:Name="txtPersonId" Placeholder="PersonId Update and Delete"></Entry>
<Entry x:Name="txtName" Placeholder="Enter Person Name"></Entry>
<StackLayout HorizontalOptions="CenterAndExpand" Orientation="Horizontal">
<Button x:Name="btnAdd" WidthRequest="200" Text="Add" Clicked="BtnAdd_Clicked" />
<Button x:Name="btnRead" WidthRequest="200" Text="Read" Clicked="BtnRead_Clicked" />
</StackLayout>
<StackLayout HorizontalOptions="CenterAndExpand" Orientation="Horizontal">
<Button x:Name="btnUpdate" WidthRequest="200" Text="Update" Clicked="BtnUpdate_Clicked" />
<Button x:Name="btnDelete" WidthRequest="200" Text="Delete" Clicked="BtnDelete_Clicked" />
</StackLayout>
<ListView x:Name="lstPersons">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Name}" Detail="{Binding PersonId}"></TextCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</StackLayout>
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub


Click the Play button to try it out.



NuGet Packages

Now, add the following NuGet Packages.


  • LiteDB


Add LiteDB NuGet

Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search "LiteDB" and add Package. Remember to install it for .NET Standard project.



Create a Model

In this step, you can create a model to Create a Table.

Person.cs

namespace XamarinLiteDB
{
public class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
}
}
view raw Person.cs hosted with ❤ by GitHub




Get Local File Path

Now, Write the following code to get local file path for storing the database in App.xaml.cs

App.xaml.cs

static LiteDBHelper db;
public static LiteDBHelper LiteDB
{
get
{
if (db == null)
{
db = new LiteDBHelper(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XamarinLiteDB.db"));
}
return db;
}
}
view raw App.xaml.cs hosted with ❤ by GitHub



Create a Table 

In this step, Write the following code to create a LiteCollection and create the table in LiteDBHelper.cs constructor.

LiteDBHelper.cs

protected LiteCollection<Person> personCollection;
public LiteDBHelper(string dbPath)
{
using (var db = new LiteDatabase(dbPath))
{
personCollection = db.GetCollection<Person>("Persons");
}
}
view raw LiteDBHelper.cs hosted with ❤ by GitHub



Check Database 

if you need to explore your LiteDB database download LiteDBViewer 

https://github.com/falahati/LiteDBViewer/releases

Example 



Read All

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

LiteDBHelper.cs

//Get All Persons
public List<Person> GetAllPersons()
{
var persons= new List<Person>(personCollection.FindAll());
return persons;
}
view raw LiteDBHelper.cs hosted with ❤ by GitHub


MainPage.Xaml.cs

//Get All Persons
var personList=App.LiteDB.GetAllPersons();
if(personList.Count!=0)
{
lstPersons.ItemsSource = personList;
}



Click the Play button to try it out.




Insert

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

//Add New Person
public void AddPerson(Person person)
{
personCollection.Insert(person);
}
private void BtnAdd_Clicked(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtName.Text))
{
Person person = new Person()
{
Name = txtName.Text
};
//Add New Person
App.LiteDB.AddPerson(person);
txtName.Text = string.Empty;
DisplayAlert("Success", "Person Added", "OK");
//Get All Persons
var personList = App.LiteDB.GetAllPersons();
if (personList.Count != 0)
{
lstPersons.ItemsSource = personList;
}
}
}



Click the Play button to try it out.




Read

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

//Get Person
public Person GetPerson(int personId)
{
var person = GetAllPersons().Where(a => a.PersonId == personId).FirstOrDefault();
return person;
}
private void BtnRead_Clicked(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty(txtPersonId.Text))
{
var person= App.LiteDB.GetPerson(Convert.ToInt32(txtPersonId.Text));
if(person!=null)
{
txtName.Text = person.Name;
DisplayAlert("Success", "Person Name: "+person.Name, "OK");
}
else
{
DisplayAlert("Faild", "Person is not available", "OK");
}
}
}



Click the Play button to try it out.




Update

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

//Update Person
public void UpdatePerson(Person person)
{
personCollection.Update(person);
}
private void BtnUpdate_Clicked(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtPersonId.Text))
{
Person person = new Person()
{
PersonId = Convert.ToInt32(txtPersonId.Text),
Name = txtName.Text
};
//Update person
App.LiteDB.UpdatePerson(person);
txtName.Text = string.Empty;
txtPersonId.Text = string.Empty;
DisplayAlert("Success", "Person Updated", "OK");
//Get All Persons
var personList = App.LiteDB.GetAllPersons();
if (personList.Count != 0)
{
lstPersons.ItemsSource = personList;
}
}
}



Click the Play button to try it out.




Delete

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

//Delete Person
public void DeletePerson(int personId)
{
personCollection.Delete(a => a.PersonId == personId);
}
private void BtnDelete_Clicked(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty(txtPersonId.Text))
{
//Delete Person
App.LiteDB.DeletePerson(Convert.ToInt32(txtPersonId.Text));
txtPersonId.Text = string.Empty;
DisplayAlert("Warning", "Person Deleted!", "OK");
//Get All Persons
var personList = App.LiteDB.GetAllPersons();
if (personList.Count != 0)
{
lstPersons.ItemsSource = personList;
}
}
}


Click the Play button to try it out.




Full code

LiteDBHelper.cs

using LiteDB;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace XamarinLiteDB
{
public class LiteDBHelper
{
protected LiteCollection<Person> personCollection;
public LiteDBHelper(string dbPath)
{
using (var db = new LiteDatabase(dbPath))
{
personCollection = db.GetCollection<Person>("Persons");
}
}
//Get All Persons
public List<Person> GetAllPersons()
{
var persons= new List<Person>(personCollection.FindAll());
return persons;
}
//Add New Person
public void AddPerson(Person person)
{
personCollection.Insert(person);
}
//Update Person
public void UpdatePerson(Person person)
{
personCollection.Update(person);
}
//Get Person
public Person GetPerson(int personId)
{
var person = GetAllPersons().Where(a => a.PersonId == personId).FirstOrDefault();
return person;
}
//Delete Person
public void DeletePerson(int personId)
{
personCollection.Delete(a => a.PersonId == personId);
}
}
}
view raw LiteDBHelper.cs hosted with ❤ by GitHub


MainPage.Xaml.cs

using Xamarin.Forms;
namespace XamarinLiteDB
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
//Get All Persons
var personList=App.LiteDB.GetAllPersons();
if(personList.Count!=0)
{
lstPersons.ItemsSource = personList;
}
}
private void BtnAdd_Clicked(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtName.Text))
{
Person person = new Person()
{
Name = txtName.Text
};
//Add New Person
App.LiteDB.AddPerson(person);
txtName.Text = string.Empty;
DisplayAlert("Success", "Person Added", "OK");
//Get All Persons
var personList = App.LiteDB.GetAllPersons();
if (personList.Count != 0)
{
lstPersons.ItemsSource = personList;
}
}
}
private void BtnRead_Clicked(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty(txtPersonId.Text))
{
var person= App.LiteDB.GetPerson(Convert.ToInt32(txtPersonId.Text));
if(person!=null)
{
txtName.Text = person.Name;
DisplayAlert("Success", "Person Name: "+person.Name, "OK");
}
else
{
DisplayAlert("Faild", "Person is not available", "OK");
}
}
}
private void BtnUpdate_Clicked(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtPersonId.Text))
{
Person person = new Person()
{
PersonId = Convert.ToInt32(txtPersonId.Text),
Name = txtName.Text
};
//Update person
App.LiteDB.UpdatePerson(person);
txtName.Text = string.Empty;
txtPersonId.Text = string.Empty;
DisplayAlert("Success", "Person Updated", "OK");
//Get All Persons
var personList = App.LiteDB.GetAllPersons();
if (personList.Count != 0)
{
lstPersons.ItemsSource = personList;
}
}
}
private void BtnDelete_Clicked(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty(txtPersonId.Text))
{
//Delete Person
App.LiteDB.DeletePerson(Convert.ToInt32(txtPersonId.Text));
txtPersonId.Text = string.Empty;
DisplayAlert("Warning", "Person Deleted!", "OK");
//Get All Persons
var personList = App.LiteDB.GetAllPersons();
if (personList.Count != 0)
{
lstPersons.ItemsSource = personList;
}
}
}
}
}



I hope you have understood, how to use LiteDB Database with CRUD Operations in Xamarin.Forms. Thanks for reading. Please share your comments and feedback.

Happy Coding :)

2 comments:

  1. i am using xamarin forms. how to access the litedb from android emulator

    this the path i am getting /data/user/0/org.mohi/files/MohiSocialWorker.db

    ReplyDelete
  2. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Scrum Master during this lockdown period everyone can use it wisely.
    CSM online

    ReplyDelete