Anda di halaman 1dari 19

Modul 5 SQL Lite dan REST Services

Pendahuluan

Pada modul ini akan dibahas bagaimana bekerja dengan media penyimpanan lokal berupa database
yaitu SQL Lite untuk menyimpan persistance data pada perangkat Android. Modul ini juga akan
membahas bagaimana cara untuk bekerja dengan REST Services pada aplikasi backend.

Bekerja dengan SQL Lite

Pada subbab berikut akan dibahas bagaimana cara untuk menyimpan data secara lokal menggunakan
database SQLite. Contoh aplikasi yang akan dibuat adalah aplikasi untuk menyimpan dan memanipulasi
data Pegawai.

Practice #5.1 Membuat Aplikasi Daftar Pegawai dengan SQLite


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 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 System;
using Xamarin.Forms;
using SampleSQLite.Droid;
using System.IO;
using SampleSQLite;

[assembly: Dependency(typeof(SqliteService))]
namespace SampleSQLite.Droid
{
public class SqliteService : ISQLIte
{
public SqliteService() { }
public SQLite.Net.SQLiteConnection GetConnection()
{
var sqliteFilename = "Pegawai.db3";
string documentsPath =
Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path = Path.Combine(documentsPath, sqliteFilename);
Console.WriteLine(path);
if (!File.Exists(path)) File.Create(path);
var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
var conn = new SQLite.Net.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.


Menggunakan REST Services pada Xamarin Forms

Pada contoh dibawah ini REST Services yang dibangun menggunakan framework ASP.NET Web API yang
sudah dipasang pada layanan komputasi awan Microsoft Azure.

Adapun alamat dari REST Service yang digunakan: http://actservices.azurewebsites.net/api/TodoItem/

Untuk pengecekan apakah Web Services tersebut dapat berjalan, anda dapat menggunakan tool Fiddler.
Anda dapat mengunduh tools fiddler secara gratis pada tautan berikut ini
https://www.telerik.com/download/fiddler.

#Practice 5.2 Mengakses REST Services Menggunakan Fiddler.


1. Langkah pertama yang akan dilakukan adalah melakukan percobaan untuk mengakses contoh backend
services yang sudah tersedia.
2. Buka tools fiddler, kemudian arahkan ke tab Composer. Pilih method GET untuk mengambil dari dari REST
Services, kemudian tambahkan alamat berikut http://actservices.azurewebsites.net/api/TodoItem/.
Kemudian tekan tombol Execute.
3. Pada jendela bagian kiri akan ditampilkan hasil-nya. Status yang tertera adalah 200 OK yang menunjukan
bahwa request ke server berhasil.
4. Data JSON yang dikembalikan dapat dilihat pada gambar dibawah ini.
#Practice 5.3 Mengakses REST Services dari Xamarin Forms.
1. Buat project Xamarin Forms baru dengan nama TodoREST.
2. Klik kanan pada solution kemudian pilih Manage Nuget Package for Solution. Kemudian tambahkan library
Microsoft.Bcl.Build, Microsoft.Net.Http, dan Newtonsoft.Json.
3. Pada project Portable, tambahkan folder dengan nama Models. Kemudian tambahkan class dengan nama
TodoItem.cs. Class ini akan digunakan untuk membuat objek yang dapat menampung data dari REST
Services. Tambahkan kode c# berikut:

namespace TodoREST
{
public class TodoItem
{
public string ID { get; set; }
public string Name { get; set; }
public string Notes { get; set; }
public bool Done { get; set; }
}
}

4. Pada project portable, tambahkan juga class dengan nama Constants.cs untuk menyimpan alamat url dari
REST Services.

public static class Constants


{
public static string RestUrl =
"http://actservices.azurewebsites.net/api/TodoItem/{0}";
}

5. Pada project portable, tambahkan foder dengan nama Data. Kemudian pada folder tersebut tambahkan
interface baru dengan nama IRestService.cs. Interface ini berisi method-method yang akan digunakan untuk
menampilkan, menambahkan, mengedit, dan mendelete data.

using System.Threading.Tasks;
using TodoREST.Models;

namespace TodoREST.Data
{
public interface IRestService
{
Task<List<TodoItem>> RefreshDataAsync();
Task SaveTodoItemAsync(TodoItem item, bool isNewItem);
Task DeleteTodoItemAsync(string id);
}
}

6. Pada folder Data, tambahkan class dengan nama RestServices.cs. Class ini digunakan untuk mengakses
REST Services menggunakan class HttpClient dan menampung datanya kedalam objek koleksi yang sudah
disediakan.

using System;

using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using TodoREST.Data;
namespace TodoREST.Data

{
public class RestService : IRestService
{
HttpClient client;

public List<TodoItem> Items { get; private set; }


public RestService()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
}

public async Task<List<TodoItem>> RefreshDataAsync()


{
Items = new List<TodoItem>();
var uri = new Uri(string.Format(Constants.RestUrl, string.Empty));

try
{
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Items = JsonConvert.DeserializeObject<List<TodoItem>>(content);
}
}
catch (Exception ex)
{
Debug.WriteLine(@"Kesalahan {0}", ex.Message);
}

return Items;
}

public async Task SaveTodoItemAsync(TodoItem item, bool isNewItem = false)


{
var uriPost = new Uri(string.Format(Constants.RestUrl, string.Empty));
var uriPut = new Uri(string.Format(Constants.RestUrl, item.ID));
try
{
var json = JsonConvert.SerializeObject(item);
var content = new StringContent(json, Encoding.UTF8, "application/json");

HttpResponseMessage response = null;


if (isNewItem)
{
response = await client.PostAsync(uriPost, content);
}
else
{
response = await client.PutAsync(uriPut, content);
}

if (response.IsSuccessStatusCode)
{
Debug.WriteLine(@"TodoItem berhasil disimpan.");
}

}
catch (Exception ex)
{
Debug.WriteLine(@"Kesalahan {0}", ex.Message);
}
}

public async Task DeleteTodoItemAsync(string id)


{
var uri = new Uri(string.Format(Constants.RestUrl, id));

try
{
var response = await client.DeleteAsync(uri);

if (response.IsSuccessStatusCode)
{
Debug.WriteLine(@"TodoItem berhasil didelete.");
}

}
catch (Exception ex)
{
Debug.WriteLine(@"Kesalahan {0}", ex.Message);
}
}
}
}

7. Class diatas berisi method-method untuk mengakses REST Services yang digunakan untuk menampilkan,
menambah, mengedit, dan mendelete data.
8. Pada folder Data, tambahkan class dengan nama TodoItemManager.cs. Class ini berfungsi untuk
memanggil method pada class RestServices.cs.

using System.Collections.Generic;
using System.Threading.Tasks;
using TodoREST.Models;

namespace TodoREST.Data
{
public class TodoItemManager
{
IRestService restService;

public TodoItemManager(IRestService service)


{
restService = service;
}

public Task<List<TodoItem>> GetTasksAsync()


{
return restService.RefreshDataAsync();
}

public Task SaveTaskAsync(TodoItem item, bool isNewItem = false)


{
return restService.SaveTodoItemAsync(item, isNewItem);
}

public Task DeleteTaskAsync(TodoItem item)


{
return restService.DeleteTodoItemAsync(item.ID);
}
}
}

9. Langkah selanjutnya adalah menampilkan data yang sudah diambil dari REST Services. Untuk itu pada
project portable buat folder baru dengan nama Views.
10. Pada folder Views tambahkan halaman xaml dengan nama TodoListPage.xaml. Halaman ini digunakan
untuk menampilkan informasi todolist pada kontrol ListView.

<?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="TodoREST.TodoListPage"
Title="Todo">
<ContentPage.ToolbarItems>
<ToolbarItem Text="+" Clicked="OnAddItemClicked">
<ToolbarItem.Icon>
<OnPlatform x:TypeArguments="FileImageSource" Android="plus.png" />
</ToolbarItem.Icon>
</ToolbarItem>
</ContentPage.ToolbarItems>
<ContentPage.Content>
<ListView x:Name="listView" ItemSelected="OnItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="20,0,0,0"
HorizontalOptions="StartAndExpand" Orientation="Horizontal">
<Label Text="{Binding Name}" VerticalTextAlignment="Center" />
<Image Source="check.png" IsVisible="{Binding Done}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage.Content>
</ContentPage>

11. Tambahkan gambar plus.png dan icon.png pada project Droid (folder Resources\drawable). Dengan klik
kanan pada drawable > Add > Existing Item... > kemudian cari gambar icon

12. Kemudian tambahkan kode berikut pada file TodoListPage.xaml.cs.

using Xamarin.Forms;
namespace TodoREST
{
public partial class TodoListPage : ContentPage
{
bool alertShown = false;

public TodoListPage()
{
InitializeComponent();
}

protected async override void OnAppearing()


{
base.OnAppearing();
listView.ItemsSource = await App.TodoManager.GetTasksAsync();
}

void OnAddItemClicked(object sender, EventArgs e)


{
var todoItem = new TodoItem()
{
ID = Guid.NewGuid().ToString()
};
var todoPage = new TodoItemPage(true);
todoPage.BindingContext = todoItem;
Navigation.PushAsync(todoPage);
}

void OnItemSelected(object sender, SelectedItemChangedEventArgs e)


{
var todoItem = e.SelectedItem as TodoItem;
var todoPage = new TodoItemPage();
todoPage.BindingContext = todoItem;
Navigation.PushAsync(todoPage);
}
}
}
13. Kode diatas berisi method yang digunakan untuk menampilkan data todo list kedalam kontrol ListView, dan
menambahkan event ketika list tersebut dipilih.
14. Tambahkan halaman xaml baru dengan nama TodoItemPage.xaml. Halaman ini digunakan untuk
menampilkan detail todo, mengedit, dan mendelete data.

<?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="TodoREST.TodoItemPage"
Title="Todo">
<ContentPage.Content>
<StackLayout VerticalOptions="StartAndExpand">
<Label Text="Name" />
<Entry x:Name="nameEntry" Text="{Binding Path=Name}"
Placeholder="task name" />
<Label Text="Notes" />
<Entry x:Name="notesEntry" Text="{Binding Path=Notes}" />
<Label Text="Done" />
<Switch x:Name="doneSwitch" IsToggled="{Binding Path=Done}" />
<Button Text="Save" Clicked="OnSaveActivated" />
<Button Text="Delete" Clicked="OnDeleteActivated" />
<Button Text="Cancel" Clicked="OnCancelActivated" />
</StackLayout>
</ContentPage.Content>
</ContentPage>

15. Tambahkan kode berikut pada file TodoItemPage.xaml.cs.

using System;

using TodoREST.Models;

using Xamarin.Forms;

namespace TodoREST
{
public partial class TodoItemPage : ContentPage
{
bool isNewItem;

public TodoItemPage(bool isNew = false)


{
InitializeComponent();
isNewItem = isNew;
}

async void OnSaveActivated(object sender, EventArgs e)


{
var todoItem = (TodoItem)BindingContext;
await App.TodoManager.SaveTaskAsync(todoItem, isNewItem);
await Navigation.PopAsync();
}

async void OnDeleteActivated(object sender, EventArgs e)


{
var todoItem = (TodoItem)BindingContext;
await App.TodoManager.DeleteTaskAsync(todoItem);
await Navigation.PopAsync();
}

void OnCancelActivated(object sender, EventArgs e)


{
Navigation.PopAsync();
}
}
}
16. Langkat terakhir tambahkan kode berikut pada file App.xaml.cs pada project portable.

using TodoREST.Data;
using Xamarin.Forms;

public class App : Application


{
public static TodoItemManager TodoManager { get; private set; }
public static ITextToSpeech Speech { get; set; }

public App()
{
TodoManager = new TodoItemManager(new RestService());
MainPage = new NavigationPage(new TodoListPage());
}
}
17. Tekan tombol F5 untuk menjalankan aplikasi pada emulator Android.

Anda mungkin juga menyukai