Loading...

Consuming RESTful API's in Xamarin.Android

View: 327    Dowload: 1   Comment: 0   Post by: admin   Category: Android   Fields: Other

Download  consuming-restful-api-s-in.zip (334.73 KB)

You need to Sign In to download the file consuming-restful-api-s-in.zip
If you do not have an account then Sign up for free here

In this episode, i will explain you that how we can consume RESTful API's in Xamarin.AndroidIntroduction

Today, i am very excited to show you that, how we can consume RESTful API's in Xamarin using C# and XMAL.

Background

In the last article, i had developed RESTful API's in ASP.Net with Azure database. So, first of all we need to deploy our API project to Microsoft Azure for globlly access in everywhere of world or in mobile application. Simply right click on your project and hit Publish.

The prerequisites

  • Microsoft HttpClient Nuget Package
  • Newtonsoft.Json Nuget Package

The steps given below are required to be followed in order to create a chat app in Xamarin.Android, using Visual Studio.

Step 1: Create a Project

Open Visual Studio and go to New Project-> Templates-> Visual C#-> Android-> Blank app. Give it a name like XamarinApp.

Step 2: Install Microsoft.Net.Http Nuget Package

Go to Solution Explorer-> Project Name-> References. Then, right-click "Manage NuGet Packages" and search for Microsoft.Net.Http. Install the Microsoft.Net.Http package in your project.

Step 3: Install Newtonsoft.Json Nuget Package

Similarly, install the Newtonsoft.Json package into your project.

Step 4: Create Feedback Class

Add a new class, open Solution Explorer-> Project Name-> right click to add a new item and select Class. Give it a name like Feedback and add the following code with getters setters properties and make it public.

(FileName: Feedback.cs)

public class Feedback
    {
        public string ID { get; set; }
        public string Email { get; set; }
        public string Subject { get; set; }
        public string Message { get; set; }
    }

Step 5: Create a AddFeedback Layout

Add a new layout by going to Solution Explorer-> Project Name-> Resources-> Layout. Right click to add a new item, select layout, and give it the name AddFeedback.axml. Open this layout file and add the following code in the source.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:padding="20dp">
  <TextView

      android:text="User Feedback Form"

      android:textAppearance="?android:attr/textAppearanceMedium"

      android:layout_width="match_parent"

      android:layout_height="wrap_content"

      android:layout_marginTop="10dp"

      android:gravity="center" />
  <EditText

      android:hint="your email here !"

      android:layout_width="match_parent"

      android:layout_height="wrap_content"

      android:id="@+id/edtEmail" />
  <EditText

      android:hint="your subject here !"

      android:layout_width="match_parent"

      android:layout_height="wrap_content"

      android:id="@+id/edtSubject" />
  <EditText

      android:hint="your message here !"

      android:layout_width="match_parent"

      android:layout_height="wrap_content"

      android:layout_weight="1"

      android:id="@+id/edtMessage" />
  <Button

      android:text="Send"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:layout_gravity="center"

      android:id="@+id/btnSend" />
</LinearLayout>

Step 6: Create AddFeedback Activity

Add a new Activity. For this, open Solution Explorer-> Project Name-> right click to add a new item and select Activity. Give it a name like AddFeedback and add the following code, using the appropriate namespaces.

(FileName: AddFeedback)

using Android.App;
using Android.OS;
using Android.Widget;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace XamarinApp.Activities
{
    [Activity(Label = "AddFeedback")]
    public class AddFeedback : Activity
    {
        private EditText edtEmail, edtSubject, edtMessage;
        private Button btnSend;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.AddFeedback);
            edtEmail = FindViewById<EditText>(Resource.Id.edtEmail);
            edtSubject = FindViewById<EditText>(Resource.Id.edtSubject);
            edtMessage = FindViewById<EditText>(Resource.Id.edtMessage);
            btnSend = FindViewById<Button>(Resource.Id.btnSend);
            btnSend.Click += async delegate 
            {
                Feedback feedback = new Feedback();
                feedback.Email = edtEmail.Text;
                feedback.Subject = edtSubject.Text;
                feedback.Message = edtMessage.Text;
                HttpClient client = new HttpClient();
                string url = $"http://xamarindevelopment.azurewebsites.net/api/Feedback?Email={feedback.Email}&Subject={feedback.Subject}&Message={feedback.Message}";
                var uri = new Uri(url);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response;
                var json = JsonConvert.SerializeObject(feedback);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                response = await client.PostAsync(uri, content);
                Clear();
                if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    Toast.MakeText(this, "Your feedback is saved", ToastLength.Long).Show();
                }
                else
                {
                    Toast.MakeText(this, "Your feedback is not saved", ToastLength.Long).Show();
                }
            };
        }
        void Clear()
        {
            edtEmail.Text = "";
            edtMessage.Text = "";
            edtSubject.Text = "";
        }
    }
}

Step 7: Create a UpdateFeedback Layout

Add a new layout by going to Solution Explorer-> Project Name-> Resources-> Layout. Right click to add a new item, select layout, and give it the name UpdateFeedback.axml. Open this layout file and add the following code in the source.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="match_parent"

    android:layout_height="match_parent">
    <TextView

        android:text="Feedback Update Form"

        android:textAppearance="?android:attr/textAppearanceMedium"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginTop="10dp"

        android:gravity="center" />
    <TableRow

        android:layout_marginTop="10dp"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:id="@+id/tableRow1">
        <TextView

            android:text="ID  :"

            android:textAppearance="?android:attr/textAppearanceMedium"

            android:id="@+id/textView2"

            android:layout_width="wrap_content" />
        <EditText

            android:layout_column="1"

            android:id="@+id/edt_updateId"

            android:layout_width="250dp"

            android:layout_height="wrap_content"

            android:hint="Your ID here !" />
        <Button

            android:text="GET"

            android:layout_column="2"

            android:id="@+id/btngetID"

            android:layout_width="wrap_content"

            android:layout_marginLeft="10dp" />
    </TableRow>
    <EditText

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:id="@+id/edt_updateEmail"

        android:hint="Email"

        android:layout_marginTop="10dp" />
    <EditText

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:id="@+id/edt_updateSubject"

        android:hint="Subject"

        android:layout_marginTop="10dp" />
    <EditText

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_weight="1"

        android:id="@+id/edt_updateMessage"

        android:hint="Message"

        android:layout_marginTop="10dp" />
    <Button

        android:text="UPDATE"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/btn_update"

        android:layout_marginTop="20dp"

        android:layout_gravity="center" />
</LinearLayout>

Step 8: Create UpdateFeedback Activity

Add a new Activity. For this, open Solution Explorer-> Project Name-> right click to add a new item and select Activity. Give it a name like UpdateFeedback and add the following code, using the appropriate namespaces.

(FileName: UpdateFeedback)

using Android.App;
using Android.OS;
using Android.Widget;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace XamarinApp.Activities
{
    [Activity(Label = "UpdateFeedback")]
    public class UpdateFeedback : Activity
    {
        EditText edtId, edtEmail, edtSubject, edtMessage;
        Button btnGet, btnUpdate;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.UpdateFeedback);
            edtId = FindViewById<EditText>(Resource.Id.edt_updateId);
            edtEmail = FindViewById<EditText>(Resource.Id.edt_updateEmail);
            edtSubject = FindViewById<EditText>(Resource.Id.edt_updateSubject);
            edtMessage = FindViewById<EditText>(Resource.Id.edt_updateMessage);
            btnGet = FindViewById<Button>(Resource.Id.btngetID);
            btnUpdate = FindViewById<Button>(Resource.Id.btn_update);
            btnGet.Click += async delegate 
            {
                Feedback feedback = null;
                HttpClient client = new HttpClient();
                string url = "http://xamarindevelopment.azurewebsites.net/api/Feedback/" + edtId.Text.ToString();
                var result = await client.GetAsync(url);
                var json = await result.Content.ReadAsStringAsync();
                try
                {
                    feedback = Newtonsoft.Json.JsonConvert.DeserializeObject<Feedback>(json);
                }
                catch (Exception ex) { }
                if (feedback == null)
                {
                    Toast.MakeText(this, json, ToastLength.Short).Show();
                }
                else
                {
                    edtSubject.Text = feedback.Subject;
                    edtMessage.Text = feedback.Message;
                    edtEmail.Text = feedback.Email;
                }
            };

            btnUpdate.Click += async delegate 
            {
                Feedback feedback = new Feedback();
                feedback.ID = edtId.Text;
                feedback.Email = edtEmail.Text;
                feedback.Subject = edtSubject.Text;
                feedback.Message = edtMessage.Text;
                HttpClient client = new HttpClient();
                string url = $"http://xamarindevelopment.azurewebsites.net/api/Feedback/{feedback.ID}?Email={feedback.Email}&Subject={feedback.Subject}&Message={feedback.Message}";
                var uri = new Uri(url);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response;
                var json = JsonConvert.SerializeObject(feedback);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                response = await client.PostAsync(uri, content);
                Clear();
                if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    Toast.MakeText(this, "Your feedback is updated", ToastLength.Long).Show();
                }
                else
                {
                    Toast.MakeText(this, "Your feedback is not updated", ToastLength.Long).Show();
                }
            };

            void Clear()
            {
                edtEmail.Text = "";
                edtMessage.Text = "";
                edtSubject.Text = "";
            }
        }
    }
}

Step 9: Create a DeleteFeedback Layout

Similarly, add a new layout by going to Solution Explorer-> Project Name-> Resources-> Layout. Right click to add a new item, select layout, and give it the name DeleteFeedback.axml. Open this layout file and add the following code in the source.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="match_parent"

    android:layout_height="match_parent">
  <TextView

      android:text="Feedback Delete"

      android:textAppearance="?android:attr/textAppearanceMedium"

      android:layout_width="match_parent"

      android:layout_height="wrap_content"

      android:layout_marginTop="10dp"

      android:gravity="center" />
  <EditText

      android:hint="Your ID here !"

      android:layout_width="match_parent"

      android:layout_height="wrap_content"

      android:id="@+id/edtId" />
  <Button

      android:text="Delete Feedback"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:layout_gravity="center"

      android:id="@+id/btnDelete" />
</LinearLayout>

Step 10: Create DeleteFeedback Activity

Again, add a new Activity. For this, open Solution Explorer-> Project Name-> right click to add a new item and select Activity. Give it a name like DeleteFeedback and add the following code, using the appropriate namespaces.

(FileName: DeleteFeedback)

 
using Android.App;
using Android.OS;
using Android.Widget;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace XamarinApp.Activities
{
    [Activity(Label = "DeleteFeedback")]
    public class DeleteFeedback : Activity
    {
        private EditText edtId;
        private Button btnDel;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.DeleteFeedback);
            edtId = FindViewById<EditText>(Resource.Id.edtId);
            btnDel = FindViewById<Button>(Resource.Id.btnDelete);
            btnDel.Click += async delegate 
            {
                Feedback feedback = new Feedback();
                feedback.ID = edtId.Text;
                HttpClient client = new HttpClient();
                string url = "http://xamarindevelopment.azurewebsites.net/api/Feedback/"+edtId.Text.ToString();
                var uri = new Uri(url);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response;
                var json = JsonConvert.SerializeObject(feedback);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                response = await client.PostAsync(uri, content);
                if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    Toast.MakeText(this, "Your feedback is deleted", ToastLength.Short).Show();
                }
                else
                {
                    Toast.MakeText(this, "Your feedback is not deleted", ToastLength.Short).Show();
                }
            };
        }
    }
}

Step 11: Main Layout

Open Solution Explorer-> Project Name-> Resources-> Layout-> Main.axml. Open this main layout file and add the following code.

(File Name: Main.axml , Folder Name: Layout)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="match_parent"

    android:layout_height="match_parent">
    <Button

        android:text="Add Feedback"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:id="@+id/btnAdd" />
    <Button

        android:text="Update Feedback"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:id="@+id/btnUpdate" />
    <Button

        android:text="Delete Feedback"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:id="@+id/btnDelete" />
</LinearLayout>

Step 12: Main Activity Class

Now, go to Solution Explorer-> Project Name-> MainActivity and add the following code to main activity with appropriate namespaces.

(FileName: MainActivity)

using Android.App;
using Android.OS;
using Android.Widget;
using XamarinApp.Activities;

namespace XamarinApp
{
    [Activity(Label = "XamarinApp", MainLauncher = true)]
    public class MainActivity : Activity
    {
        private Button btnAdd, btnUpdate, btnDelete;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            btnAdd = FindViewById<Button>(Resource.Id.btnAdd);
            btnDelete = FindViewById<Button>(Resource.Id.btnDelete);
            btnUpdate = FindViewById<Button>(Resource.Id.btnUpdate);
            btnAdd.Click += delegate { StartActivity(typeof(AddFeedback)); };
            btnDelete.Click += delegate { StartActivity(typeof(DeleteFeedback)); };
            btnUpdate.Click += delegate { StartActivity(typeof(UpdateFeedback)); };
        }
    }
}

Final Words

Finally, we are finished with our Xamarin.Android app with consuming RESTful API's that we developed in ASP.Net. Just rebuild and run the project.

Points of Interest

In this article, I demonstrated how you can create a Xamarin Android application using RESTful API's. Now you can Insert, Update , Get and Delete your feedback or data from your Azure database using Android application. 

Consuming RESTful API's in Xamarin.Android

In the last article, i had developed RESTful API's in ASP.Net with Azure database. So, first of all we need to deploy our API project to Microsoft Azure for globlly access in everywhere of world or in mobile application. Simply right click on your project and hit Publish.

Posted on 02-04-2018 

Comment:

To comment you must be logged in members.

Files with category

 
File suggestion for you
Loading...
File top downloads
Loading...
Loading...
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd