Consuming Restful Services In Xamarin.Forms - Part Two

Introduction

This article is the second part of my article - Consuming Restful Services in Xamarin.Forms Part 1

In the first part, we called a fake RESTFul service, got some data from that service and displayed it in a List View. Now, in this article we will continue where we left off and add/delete some data that we displayed in the previous part.

Code and output of part 1

XAML

  1. <ListView x:Name="Post_List">  
  2.       <ListView.ItemTemplate>  
  3.           <DataTemplate>  
  4.               <TextCell Text="{Binding title}" Detail="{Binding body}"></TextCell>  
  5.           </DataTemplate>  
  6.       </ListView.ItemTemplate>  
  7.         
  8.   </ListView>   

Code 

  1. using System.Collections.Generic;  
  2. using System.Net.Http;  
  3. using Xamarin.Forms;  
  4. using Newtonsoft.Json;  
  5. using System.Collections.ObjectModel;  
  6.   
  7. namespace XamarinApp3  
  8. {  
  9.   
  10.     public class Post  
  11.     {  
  12.         public int userId { get; set; }  
  13.         public int id { get; set; }  
  14.         public string title { get; set; }  
  15.         public string body { get; set; }  
  16.     }  
  17.   
  18.   
  19.     public partial class MainPage : ContentPage  
  20.     {  
  21.         private const string url = "https://jsonplaceholder.typicode.com/posts";  
  22.         private HttpClient _Client = new HttpClient();  
  23.         private ObservableCollection<Post> _post;  
  24.   
  25.         public MainPage()  
  26.         {  
  27.               
  28.             InitializeComponent();  
  29.           
  30.         }  
  31.   
  32.         protected override async void OnAppearing()  
  33.         {  
  34.             var content = await _Client.GetStringAsync(url);  
  35.             var post = JsonConvert.DeserializeObject<List<Post>>(content);  
  36.             _post = new ObservableCollection<Post>(post);  
  37.             Post_List.ItemsSource = _post;  
  38.             base.OnAppearing();  
  39.         }  
  40.     }  
  41. }  

Output

Xamarin.Forms

Now, let's start by modifying our XAML and add two buttons for "Add" and "Delete" operations respectively in our page.

XAML 

  1. <StackLayout>  
  2.     <StackLayout Orientation="Horizontal">  
  3.         <Button Text="Add" Clicked="OnAdd"></Button>  
  4.         <Button Text="Delete" Clicked="OnDelete"></Button>  
  5.     </StackLayout>  
  6.   
  7. <ListView x:Name="Post_List">  
  8.     <ListView.ItemTemplate>  
  9.         <DataTemplate>  
  10.             <TextCell Text="{Binding title}" Detail="{Binding body}"></TextCell>  
  11.         </DataTemplate>  
  12.     </ListView.ItemTemplate>  
  13.   
  14. </ListView>  
  15. </StackLayout>  

Output

Xamarin.Forms

Here, you can see that both the buttons are shown on your View. Now, add the functionality on click event of both the buttons.

Add data

 Code 

  1. private async void OnAdd(object sender, System.EventArgs e)  
  2. {  
  3.     var post = new Post() { title = "Title" + DateTime.Now.Ticks, body = "Body"};  
  4.     _post.Insert(0, post);  
  5.     var content = JsonConvert.SerializeObject(post);  
  6.    await _Client.PostAsync(url, new StringContent(content));  
  7.  

Explanation

Here, you can see that we created an object of post class and set its title and body. Now, we are going to add this line ( Move towards the second line). This code will add data in our observable collection. And in the third line, we serialize the post before saving any data to the server. And in the last line, we have sent the post async request to our http client with the end point and content. This line will post the given data to the endpoint.

Output

Xamarin.Forms

Here, you will see that after clicking on the "Add" button, our data is posted to the server and shown in our List View.

Note

*As we are using a fake RESTFul service, the data which we save through our Add button is not persistent. When we come back to our application, this data is not here.

Delete Data

Now, move towards the functionality of Delete.

Code 

  1. private async void OnDelete(object sender, System.EventArgs e)  
  2.         {  
  3.             var post = _post[0];  
  4.             _post.Remove(post);  
  5.            await _Client.DeleteAsync(url + "/" + post.id);  
  6.         }   

Explanation

In the first line, we are pointing to first value in our list view. In the second line, this first data is removed from our list. In the third line, we send the Delete async request to our URL. This URL is completed by adding the id of post which we want to delete.

Output

Xamarin.Forms

Just see the first value in our list view then click on "Delete" button. You will see that this data is deleted from the list.

Output by clicking on delete button

Xamarin.Forms

Here, you can see that after clicking the Delete button, the first value is deleted.


Similar Articles