Pada blog tutorial kali ini saya akan menjelaskan bagaimana cara untuk bekerja dengan basis data lokal sqlite menggunakan Xamarin Forms untuk target platform Android.
1. Buat Xamarin Form solution dengan nama SampleSQLite.
2. Kemudian tambahkan library SQLite-Net-PCL pada semua project agar dapat menggunakan SQLite.
3. Klik kanan pada solution ‘SampleSQLite’. Kemudian pilih NuGET package dan tambahkan paket SQLite-Net-PCL pada project portable, dan droid.

4. Pada project portable SampleSQLite tambahkan kode c# berikut untuk membuat objek interface dengan nama ISQLite yang digunakan untuk membuat method koneksi.
using SQLite.Net;
namespace SampleSQLite
{
public interface ISQLite
{
SQLiteConnection GetConnection();
}
}
5. Pada project Droid, buat class dengan nama SqliteService.cs dan tambahkan kode berikut untuk membuat db sqlite baru:
using Xamarin.Forms;
using System.IO;
using SQLite.Net;
using SampleSQLite.Droid;
[assembly: Dependency(typeof(SqliteService))]
namespace SampleSQLite.Droid
{
public class SqliteService : ISQLite
{
public SQLiteConnection GetConnection()
{
var sqliteFilename = "PegawaiDb.db3";
string documentPath =
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
//menyimpan data di /data/data/[your.package.name]/files
var path = Path.Combine(documentPath, sqliteFilename);
//Console.WriteLine(path);
if (!File.Exists(path))
File.Create(path);
var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
var conn = new SQLiteConnection(plat, path);
return conn;
}
}
}
6. Pada kode diatas kita akan membuat file database lokal dengan nama Pegawai.db3. File database tersebut akan disimpan kedalam folder pada device android anda yaitu pada folder /data/data/[your.package.name]/files.
7. Pada project portable tambahkan class dengan nama Employee.cs yang akan digunakan untuk menyimpan data pegawai pada database SQLite.
using SQLite.Net.Attributes;
using System;
namespace SampleSQLite
{
public class Employee
{
[PrimaryKey, AutoIncrement]
public long EmpId { get; set; }
[NotNull]
public string EmpName { get; set; }
public string Designation { get; set; }
public string Department { get; set; }
public string Qualification { get; set; }
}
}
8. Keyword PrimaryKey menandakan bahwa field EmpId adalah primary key. Autoincrement menunjukan bahwa kode EmpId akan digenerate otomatis oleh SQLite secara berurutan.
9. Pada project portable tambahkan juga class dengan nama DataAccess.cs. Kemudian tambahkan kode berikut:
using SQLite.Net;
using System.Collections.Generic;
using Xamarin.Forms;
namespace SampleSQLite
{
public class DataAccess
{
SQLiteConnection dbConn;
public DataAccess()
{
dbConn = DependencyService.Get<ISQLIte>().GetConnection();
dbConn.CreateTable<Employee>();
}
public List<Employee> GetAllEmployees()
{
return dbConn.Query<Employee>("Select * From [Employee]");
}
public int SaveEmployee(Employee aEmployee)
{
return dbConn.Insert(aEmployee);
}
public int DeleteEmployee(Employee aEmployee)
{
return dbConn.Delete(aEmployee);
}
public int EditEmployee(Employee aEmployee)
{
return dbConn.Update(aEmployee);
}
}
}
10. Kode diatas adalah kode yang digunakan untuk membuat table baru dan perintah untuk CRUD (Create, Read, Update, Delete).
11. Pada project portable tambahkan juga kode berikut pada file App.xaml.cs.
namespace SampleSQLite
{
public partial class App : Application
{
private static DataAccess dbUtils;
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new ManageEmployee());
}
public static DataAccess DBUtils
{
get
{
if (dbUtils == null)
{
dbUtils = new DataAccess();
}
return dbUtils;
}
}
}
}
12. Class tersebut adalah class yang akan dijalankan untuk pertama kali ketika aplikasi tersebut dijalankan.
13. Untuk menampilkan data pegawai, buat halaman xaml baru dengan nama ManageEmployee.xaml. Kemudian tambahkan kode berikut.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="SampleSQLite.ManageEmployee">
<StackLayout>
<ListView x:Name="lstData" HasUnevenRows="false" Header="Header Value" Footer="Footer" ItemSelected="OnSelection" >
<ListView.HeaderTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal" BackgroundColor="Blue" Padding="5,5,5,5">
<Label Text="Name" FontSize="Medium" FontAttributes="Bold" TextColor="White"/>
<Label Text="Designation" FontSize="Medium" FontAttributes="Bold" TextColor="White"/>
<Label Text="Department" FontSize="Medium" FontAttributes="Bold" TextColor="White"/>
</StackLayout>
</DataTemplate>
</ListView.HeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" Padding="5,5,5,5">
<Label Text="{Binding EmpName}" FontSize="Medium" />
<Label Text="{Binding Designation}" FontSize="Medium" />
<Label Text="{Binding Department}" FontSize="Medium" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.FooterTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal" Padding="5,5,5,5">
<Button Text="Add New Employee" Clicked="OnNewClicked" />
</StackLayout>
</DataTemplate>
</ListView.FooterTemplate>
</ListView>
</StackLayout>
</ContentPage>
14. Pada kode xaml diatas ditambahkan sebuah kontrol ListView untuk menampilkan data yang akan diambil dari media penyimpanan lokal SQLIte.
15. Pada file ManageEmployee.xaml.cs tambahkan kode berikut.
namespace SampleSQLite
{
public partial class ManageEmployee : ContentPage
{
public ManageEmployee()
{
InitializeComponent();
var vList = App.DBUtils.GetAllEmployees();
lstData.ItemsSource = vList;
}
void OnSelection(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
{
return;
}
var vSelUser = (Employee)e.SelectedItem;
Navigation.PushAsync(new ShowEmplyee(vSelUser));
}
public void OnNewClicked(object sender, EventArgs args)
{
Navigation.PushAsync(new AddEmployee());
}
}
}
16. Kode diatas digunakan untuk menampilkan data pegawai yang diambil dari media penyimpanan lokal dan juga menangani event untuk memilih data yang ada pada kontrol ListView untuk ditampilkan detailnya.
17. Untuk menangani penambahan data pegawai baru, buat halaman xaml baru dengan nama AddEmployee.xaml. Kemudian tambahkan kode xaml berikut ini:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="SampleSQLite.AddEmployee">
<StackLayout>
<TableView Intent="Settings" BackgroundColor="White">
<TableRoot>
<TableSection Title="Add New Employee">
<EntryCell x:Name="txtEmpName" Label="Employee Name" Keyboard="Text" />
<EntryCell x:Name="txtDesign" Label="Designation" Keyboard="Text" />
<EntryCell x:Name="txtDepartment" Label="Department" Keyboard="Text" />
<EntryCell x:Name="txtQualification" Label="Qualification" Keyboard="Text" />
<ViewCell>
<ContentView Padding="0,0">
<ContentView.Padding>
<OnPlatform x:TypeArguments="Thickness" iOS="10,0" WinPhone="0,15,0,0" />
</ContentView.Padding>
<ContentView.Content>
<Button BackgroundColor="#fd6d6d" Text="Save" TextColor="White" Clicked="OnSaveClicked" />
</ContentView.Content>
</ContentView>
</ViewCell>
</TableSection>
</TableRoot>
</TableView>
</StackLayout>
</ContentPage>
18. Kemudian tambahka kode pada file AddEmployee.xaml.cs sebagai berikut.
using Xamarin.Forms;
namespace SampleSQLite
{
public partial class AddEmployee : ContentPage
{
public AddEmployee()
{
InitializeComponent();
}
public void OnSaveClicked(object sender, EventArgs args)
{
var vEmployee = new Employee()
{
EmpName = txtEmpName.Text,
Department = txtDepartment.Text,
Designation = txtDesign.Text,
Qualification = txtQualification.Text
};
App.DBUtils.SaveEmployee(vEmployee);
Navigation.PushAsync(new ManageEmployee());
}
}
}
19. Untuk menampilkan halaman detail pegawai per record, tambahkan halaman xaml dengan nama ShowEmployee.xaml. Halaman ini juga memiliki tombol edit dan delete record.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="SampleSQLite.ShowEmplyee">
<StackLayout>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
</Grid.ColumnDefinitions>
<Label Grid.Row ="0" Grid.Column="0" Grid.ColumnSpan="2" Text="Employee Details" />
<Label Grid.Row ="1" Grid.Column="1" Text="Name" />
<Label Grid.Row="1" Grid.Column="2" Text ="{Binding EmpName}" />
<Label Grid.Row ="2" Grid.Column="1" Text="Designation" />
<Label Grid.Row="2" Grid.Column="2" Text ="{Binding Designation}"/>
<Label Grid.Row ="3" Grid.Column="1" Text="Department" />
<Label Grid.Row="3" Grid.Column="2" Text ="{Binding Department}"/>
<Label Grid.Row ="4" Grid.Column="1" Text="Qualification" />
<Label Grid.Row="4" Grid.Column="2" Text ="{Binding Qualification}" />
<Button Grid.Row ="5" Grid.Column="1" Text="Edit Details" Clicked="OnEditClicked" />
<Button Grid.Row="5" Grid.Column="2" Text="Delete" Clicked="OnDeleteClicked" />
</Grid>
</StackLayout>
</ContentPage>
20. Kemudian tambahkan kode berikut pada file ShowEmployee.xaml.cs.
namespace SampleSQLite
{
public partial class ShowEmplyee : ContentPage
{
Employee mSelEmployee;
public ShowEmplyee(Employee aSelectedEmp)
{
InitializeComponent();
mSelEmployee = aSelectedEmp;
BindingContext = mSelEmployee;
}
public void OnEditClicked(object sender, EventArgs args)
{
Navigation.PushAsync(new EditEmployee(mSelEmployee));
}
public async void OnDeleteClicked(object sender, EventArgs args)
{
bool accepted = await DisplayAlert("Konfirmasi", "Apakah anda yakin untuk mendelete data ?", "Yes", "No");
if (accepted)
{
App.DBUtils.DeleteEmployee(mSelEmployee);
}
await Navigation.PushAsync(new ManageEmployee());
}
}
}
21. Terakhir tambahkan halaman xaml untuk mengedit data dengan nama EditEmployee.xaml. Kemudian tambahkan kode berikut:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="SampleSQLite.EditEmployee">
<StackLayout>
<TableView Intent="Settings" BackgroundColor="White">
<TableRoot>
<TableSection Title="Edit Employee">
<EntryCell x:Name="txtEmpName" Label="Employee Name" Text ="{Binding EmpName}" Keyboard="Text" />
<EntryCell x:Name="txtDesign" Label="Designation" Text ="{Binding Designation}" Keyboard="Text" />
<EntryCell x:Name="txtDepartment" Label="Department" Text ="{Binding Department}" Keyboard="Text" />
<EntryCell x:Name="txtQualification" Label="Qualification" Text ="{Binding Qualification}" Keyboard="Text" />
<ViewCell>
<ContentView Padding="0,0">
<ContentView.Padding>
<OnPlatform x:TypeArguments="Thickness" iOS="10,0" WinPhone="0,15,0,0" />
</ContentView.Padding>
<ContentView.Content>
<Button BackgroundColor="#fd6d6d" Text="Save" TextColor="White" Clicked="OnSaveClicked" />
</ContentView.Content>
</ContentView>
</ViewCell>
</TableSection>
</TableRoot>
</TableView>
</StackLayout>
</ContentPage>
22. Tambahkan kode untuk mengedit data pada file EditEmployee.xaml.cs dibawah ini.
namespace SampleSQLite
{
public partial class EditEmployee : ContentPage
{
Employee mSelEmployee;
public EditEmployee(Employee aSelectedEmp)
{
InitializeComponent();
mSelEmployee = aSelectedEmp;
BindingContext = mSelEmployee;
}
public void OnSaveClicked(object sender, EventArgs args)
{
mSelEmployee.EmpName = txtEmpName.Text;
mSelEmployee.Department = txtDepartment.Text;
mSelEmployee.Designation = txtDesign.Text;
mSelEmployee.Qualification = txtQualification.Text;
App.DBUtils.EditEmployee(mSelEmployee);
Navigation.PushAsync(new ManageEmployee());
}
}
}
23. Tekan tombol F5 untuk menjalankan program pada Android Emulator.

