Erick Kurniawan

Microsoft Certified Trainer, Microsoft MVP for +15y on Developer Technologies

[MAUI Tutorial] – Local Storage dengan SQLite

Dalam pengembangan aplikasi mobile modern, pengelolaan data lokal menjadi salah satu aspek penting yang harus diperhatikan. Ketika aplikasi membutuhkan akses data yang cepat dan dapat diandalkan tanpa bergantung pada koneksi internet, penyimpanan lokal menjadi solusi yang tepat. SQLite, sebagai salah satu database relasional yang ringan dan portabel, menawarkan kemudahan dalam pengelolaan data lokal untuk berbagai platform.

Artikel ini akan membahas bagaimana memanfaatkan SQLite sebagai solusi penyimpanan lokal dalam aplikasi yang dibangun menggunakan .NET Multi-platform App UI (MAUI). .NET MAUI, sebagai evolusi dari Xamarin.Forms, memungkinkan pengembangan aplikasi lintas platform dengan satu basis kode. Dengan mengintegrasikan SQLite ke dalam .NET MAUI, pengembang dapat membuat aplikasi yang tidak hanya responsif tetapi juga efisien dalam pengelolaan datanya.

Mari kita telusuri langkah demi langkah bagaimana mengimplementasikan SQLite dalam proyek .NET MAUI Anda, serta berbagai keuntungan yang dapat diperoleh dengan menggunakan kombinasi teknologi ini. Dari setup awal hingga manipulasi data, artikel ini akan memberikan panduan lengkap untuk memaksimalkan potensi aplikasi Anda dengan penyimpanan lokal menggunakan SQLite.

# Lab – Membuat Aplikasi Daftar Pegawai dengan SQLite

1. Buat project .NET MAUI pada Visual Studio 2022.

2. Klik kanan pada solution explore, kemudian tambahkan manage nuget package for solution.

3. Pada project tambahkan class dengan nama Employee.cs yang akan digunakan untuk menyimpan data pegawai pada database SQLite.

using SQLite;

namespace SampleMAUIApp.Bab5
{
    public class Employee
    {
        [PrimaryKey, AutoIncrement]
        public long EmpId { get; set; }
        [SQLite.NotNull]
        public string EmpName { get; set; }
        public string Designation { get; set; }
        public string Department { get; set; }
        public string Qualification { get; set; }
    }
}

4. Keyword PrimaryKey menandakan bahwa field EmpId adalah primary key. Autoincrement menunjukan bahwa kode EmpId akan digenerate otomatis oleh SQLite secara berurutan.

5. Pada project tambahkan juga class dengan nama DataAccess.cs. Kemudian tambahkan kode berikut:

using SQLite;

namespace SampleMAUIApp.Bab5
{
    public class DataAccess
    {
        SQLiteConnection database;

        public SQLiteConnection GetConnection()
        {
            SQLiteConnection sqliteConnection;
            var dbPath = Path.Combine(FileSystem.AppDataDirectory, "MyData.db");
            sqliteConnection = new SQLiteConnection(dbPath);
            return sqliteConnection;
        }

        public DataAccess()
        {
            database = GetConnection();
            database.CreateTable<Employee>();
        }

        public IEnumerable<Employee> GetAllEmployees()
        {
            return database.Query<Employee>("select * from Employee order by EmpName");
        }

        public int SaveEmployee(Employee employee)
        {
            return database.Insert(employee);
        }

        public int DeleteEmployee(Employee employee)
        {
            return database.Delete(employee);
        }

        public int EditEmployee(Employee employee)
        {
            return database.Update(employee);
        }
    }

}

6. Kode diatas adalah kode yang digunakan untuk membuat table baru dan perintah untuk CRUD (Create, Read, Update, Delete).

7. Pada project tambahkan juga kode berikut pada file App.xaml.cs. Kode dibawah ini bertujuan untuk membuat instance class static yang dapat diakses dari semua form tanpa harus membuat instance class-nya.

using SampleMAUIApp.Bab5;

namespace SampleMAUIApp
{
    public partial class App : Application
    {

        private static DataAccess dbUtils = null!;
        public static DataAccess DBUtils
        {
            get
            {
                if (dbUtils == null)
                {
                    dbUtils = new DataAccess();
                }
                return dbUtils;
            }
        }


        public App()
        {
            InitializeComponent();
        }

        protected override Window CreateWindow(IActivationState? activationState)
        {
            return new Window(new AppShell());
        }
    }
}

8. Class App adalah class yang akan dijalankan untuk pertama kali ketika aplikasi tersebut dijalankan.

9. 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://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SampleMAUIApp.Bab5.ManageEmployee"
             Title="ManageEmployee">
    <VerticalStackLayout>
        <StackLayout>
            <ListView x:Name="lstEmployee" HasUnevenRows="False" ItemSelected="LstEmployee_ItemSelected"
                      Header="Header Value" Footer="Footer">
                <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 Department}" FontSize="Medium" />
                                <Label Text="{Binding Qualification}" FontSize="Medium"/>
                                <Button Text="delete" HeightRequest="15" CommandParameter="{Binding EmpId}" Clicked="btnDeleteClick" FontSize="Micro" />
                            </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>

    </VerticalStackLayout>
</ContentPage>

10. Pada kode xaml diatas ditambahkan sebuah kontrol ListView untuk menampilkan data yang akan diambil dari media penyimpanan lokal SQLIte.

11. Pada file ManageEmployee.xaml.cs tambahkan kode berikut.

namespace SampleMAUIApp.Bab5;

public partial class ManageEmployee : ContentPage
{
    public ManageEmployee()
    {
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        lstEmployee.ItemsSource = App.DBUtils.GetAllEmployees();
    }

    private async void LstEmployee_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        if (e.SelectedItem == null)
        {
            return;
        }
        var empDetail = (Employee)e.SelectedItem;
        await Navigation.PushAsync(new ShowEmployee(empDetail));
    }

    public async void OnNewClicked(object sender, EventArgs args)
    {
        await Navigation.PushAsync(new AddEmployee());
    }

    public async void btnDeleteClick(object sender, EventArgs args)
    {
        var item = (Button)sender;
        if (item.Text == "delete")
        {
            var result = await DisplayAlert("Konfirmasi", "Apakah anda yakin akan mendelete data " + item.CommandParameter.ToString() + " ?", "Yes", "No");
            if (result)
            {
                var empId = Convert.ToInt64(item.CommandParameter.ToString());
                App.DBUtils.DeleteEmployee(new Employee { EmpId = empId });
                OnAppearing();
            }
        }
    }

}

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

13. Kode diatas juga menangani proses delete data ketika tombol delete yang ada di dalam ListView dipilih.

14. 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://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SampleMAUIApp.Bab5.AddEmployee"
             Title="AddEmployee">
    <VerticalStackLayout>
        <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.Content>
                                <Button BackgroundColor="#fd6d6d" Text="Save" TextColor="White" Clicked="OnSaveClicked"   />
                            </ContentView.Content>
                        </ContentView>
                    </ViewCell>
                </TableSection>
            </TableRoot>
        </TableView>
    </VerticalStackLayout>
</ContentPage>

15. Kemudian tambahka kode pada file AddEmployee.xaml.cs sebagai berikut.

namespace SampleMAUIApp.Bab5;

public partial class AddEmployee : ContentPage
{
    public AddEmployee()
    {
        InitializeComponent();
    }

    public async void OnSaveClicked(object sender, EventArgs args)
    {
        var newEmployee = new Employee()
        {
            EmpName = txtEmpName.Text,
            Department = txtDepartment.Text,
            Designation = txtDesign.Text,
            Qualification = txtQualification.Text
        };
        App.DBUtils.SaveEmployee(newEmployee);
        await Navigation.PushAsync(new ManageEmployee());
    }
}

16. Untuk menampilkan halaman detail pegawai per record, tambahkan halaman xaml dengan nama ShowEmployee.xaml. Halaman ini juga memiliki tombol edit record.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SampleMAUIApp.Bab5.ShowEmployee"
             Title="ShowEmployee">
    <VerticalStackLayout>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="50"/>
                <RowDefinition Height="50"/>
                <RowDefinition Height="50"/>
                <RowDefinition Height="50"/>
                <RowDefinition Height="50"/>
                <RowDefinition Height="50"/>
                <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" FontSize="Large" FontAttributes="Bold" Text="Employee Details" />
            <Label Grid.Row ="1" Grid.Column="1" Text="Name" />
            <Entry Grid.Row="1" Grid.Column="2" x:Name="txtEmpName" Text ="{Binding EmpName}" />
            <Label Grid.Row ="2" Grid.Column="1" Text="Designation" />
            <Entry Grid.Row="2" Grid.Column="2" x:Name="txtDesignation" Text ="{Binding Designation}"/>
            <Label Grid.Row ="3" Grid.Column="1" Text="Department" />
            <Entry Grid.Row="3" Grid.Column="2" x:Name="txtDepartment" Text ="{Binding Department}"/>
            <Label Grid.Row ="4" Grid.Column="1" Text="Qualification" />
            <Entry Grid.Row="4" Grid.Column="2" x:Name="txtQualification" Text ="{Binding Qualification}" />
            <Button Grid.Row ="5" Grid.Column="1" Text="Edit Details" FontSize="Small" HeightRequest="20" Clicked="OnEditClicked" />
        </Grid>

    </VerticalStackLayout>
</ContentPage>

17. Kemudian tambahkan kode berikut pada file ShowEmployee.xaml.cs.

namespace SampleMAUIApp.Bab5;

public partial class ShowEmployee : ContentPage
{
    private Employee currEmp;
    public ShowEmployee(Employee employee)
    {
        InitializeComponent();
        currEmp = employee;
        BindingContext = currEmp;
    }

    public async void OnEditClicked(object sender, EventArgs args)
    {
        currEmp.EmpName = txtEmpName.Text;
        currEmp.Department = txtDepartment.Text;
        currEmp.Designation = txtDesignation.Text;
        currEmp.Qualification = txtQualification.Text;
        App.DBUtils.EditEmployee(currEmp);
        await Navigation.PopAsync();
    }

}

18. Tekan tombol F5 untuk menjalankan program pada Emulator.

Published by

Leave a comment