how to use REST API in xamarin android...

JunCainJunCain ✭✭✭Member ✭✭✭
edited April 8 in Xamarin.Android

I fetch data from my local database using my ip address, and it works fine. And i tried to replace my url ip address with this url https://jsonplaceholder.typicode.com/todos, to try if I can't fetch data using url, but I can't fetch data, so I realize what if I upload my database into cloud, how can I fetch data from there?.Now my question is how to convert my code into rest api or web service api or something?

MainActivity.cs

  public class MainActivity : AppCompatActivity
    {
        string urlAddress = "https://jsonplaceholder.typicode.com/todos";
        string urlAddress1 = "http://myipaddress/php_config1/config.php"; // example "http://myweb.com/products";
        string urlAddress2 = "http://myipaddress/php_config2/config.php";// example "http://myweb.com/customers";



         private void Sync_Click(object sender, System.EventArgs e)
        {
            new Syncher(this, urlAddress, urlAddress1, urlAddress2).Execute();
        }
    }

Syncher.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
using Java.IO;
using Java.Lang;
using Java.Net;
using Newtonsoft.Json;
using RestSharp;
using Console = System.Console;
using Exception = System.Exception;
using Object = Java.Lang.Object;

namespace MhylesApp.Synchronizer
{
    class Syncher : AsyncTask
    {
        private Context c;
        private string urlAddress;
        private string urlAddress1, urlAddress2;
        private SynchronizationContext sc;
        //private Spinner spinner;
        //IList<string> dataList = new List<string>();
#pragma warning disable CS0618 // Type or member is obsolete
        private ProgressDialog loadingProcess;
#pragma warning restore CS0618 // Type or member is obsolete
        public Syncher(Context c, string urlAddress, string urlAddress1, string urlAddress2)
        {
            this.c = c;
            this.urlAddress = urlAddress;
            this.urlAddress1 = urlAddress1;
            this.urlAddress2 = urlAddress2;

        }
        protected override void OnPreExecute()
        {
            base.OnPreExecute();
#pragma warning disable CS0618 // Type or member is obsolete
            loadingProcess = new ProgressDialog(c);
#pragma warning restore CS0618 // Type or member is obsolete
            loadingProcess.SetTitle("Synchronizing");
            loadingProcess.SetMessage("Fetching Data...Please wait!");
            loadingProcess.SetCancelable(false);
            loadingProcess.Show();
        }
        protected override Object DoInBackground(params Object[] @params)
        {

            return this.Retrieve() + 
            this.Retrieve1() + 
            this.Retrieve2();



        }
        protected override void OnPostExecute(Object result)
        {
            base.OnPostExecute(result);
            loadingProcess.Dismiss();
            if(result == null)
            {
                Toast.MakeText(c, "Synchronizing failed!", ToastLength.Short).Show();
            }
            else
            {
                DataParser parser = new DataParser(c, result.ToString());
                parser.Execute();
            }
        }
        // Retrieving Data
        private string Retrieve()
        {
            HttpURLConnection con = Connector.Connect(urlAddress);
            if (con == null)
            {
                return null;
            }
            try
            {
                Stream stream = new BufferedStream(con.InputStream);
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
                string line = null;
                StringBuffer response = new StringBuffer();
                while ((line = bufferedReader.ReadLine()) != null)
                {
                    response.Append(line + "\n");
                }
                bufferedReader.Close();
                stream.Close();
                return response.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return null;
        }
        private string Retrieve1()
        {
            HttpURLConnection con1 = Connector.Connect1(urlAddress1);
            if (con1 == null)
            {
                return null;
            }
            try
            {
                Stream stream1 = new BufferedStream(con1.InputStream);
                BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(stream1));
                string line1 = null;
                StringBuffer response1 = new StringBuffer();
                while ((line1 = bufferedReader1.ReadLine()) != null)
                {
                    response1.Append(line1 + "\n");
                }
                bufferedReader1.Close();
                stream1.Close();
                return response1.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return null;
        }
        private string Retrieve2()
        {
            HttpURLConnection con2 = Connector.Connect2(urlAddress2);
            if (con2 == null)
            {
                return null;
            }
            try
            {
                Stream stream2 = new BufferedStream(con2.InputStream);
                BufferedReader bufferedReader2 = new BufferedReader(new InputStreamReader(stream2));
                string line2 = null;
                StringBuffer response2 = new StringBuffer();
                while ((line2 = bufferedReader2.ReadLine()) != null)
                {
                    response2.Append(line2 + "\n");
                }
                bufferedReader2.Close();
                stream2.Close();
                return response2.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return null;
        }
    }
}

Connector.cs

using System;
using System.Net;
using System.Net.Http;
using Java.Net;
using RestSharp;

namespace MhylesApp.Synchronizer
{
    class Connector
    {
        public static HttpURLConnection Connect(String urlAddress)
        {
            try
            {
                URL url = new URL(urlAddress);
                HttpURLConnection con = (HttpURLConnection)url.OpenConnection();

                //Properties
                con.RequestMethod = "GET";
                con.ConnectTimeout = 20000;
                con.ReadTimeout = 20000;
                con.DoInput = true;
                return con;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return null;
        }
        public static HttpURLConnection Connect1(String urlAddress1)
        {
            try
            {
                URL url1 = new URL(urlAddress1);
                HttpURLConnection con1 = (HttpURLConnection)url1.OpenConnection();

                //Properties
                con1.RequestMethod = "GET";
                con1.ConnectTimeout = 20000;
                con1.ReadTimeout = 20000;
                con1.DoInput = true;
                return con1;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return null;
        }
        public static HttpURLConnection Connect2(String urlAddress2)
        {
            try
            {
                URL url2 = new URL(urlAddress2);
                HttpURLConnection con2 = (HttpURLConnection)url2.OpenConnection();

                //Properties
                con2.RequestMethod = "GET";
                con2.ConnectTimeout = 20000;
                con2.ReadTimeout = 20000;
                con2.DoInput = true;
                return con2;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return null;
        }
    }
}

DataParser.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Text;
using Android.Views;
using Android.Widget;
using Java.Lang;
using MhylesApp.Database;
using Org.Json;
using Exception = System.Exception;
using Object = Java.Lang.Object;
using String = System.String;

namespace MhylesApp.Synchronizer
{
    class DataParser : AsyncTask
    {
        Context c;
        private String jsonData;
        private string listing, listing1, listing2;
#pragma warning disable CS0618 // Type or member is obsolete
        private ProgressDialog loadingProcess;
#pragma warning restore CS0618 // Type or member is obsolete
        public DataParser(Context c, /*Spinner spinner*/string jsonData)
        {
            this.c = c;
            this.jsonData = jsonData;
        }
        protected override void OnPreExecute()
        {
            base.OnPreExecute();
#pragma warning disable CS0618 // Type or member is obsolete
            loadingProcess = new ProgressDialog(c);
#pragma warning restore CS0618 // Type or member is obsolete
            loadingProcess.SetTitle("Parsing");
            loadingProcess.SetMessage("Fetching Data...Please wait!");
            loadingProcess.SetCancelable(false);
            loadingProcess.Show();
        }
        protected override Object DoInBackground(params Object[] @params)
        {
            return this.ParseData();
        }
        protected override void OnPostExecute(Object result)
        {
            base.OnPostExecute(result);
            loadingProcess.Dismiss();
            if(Integer.ParseInt(result.ToString()) == 0)
            {
#pragma warning disable CS0618 // Type or member is obsolete
                Toast.MakeText(c, Html.FromHtml("<font color='red'>Unable to parse data</font>"), ToastLength.Short).Show();
#pragma warning restore CS0618 // Type or member is obsolete
            }
            else
            {

                //ArrayAdapter<string> adapter = new ArrayAdapter<string>(c, Android.Resource.Layout.SimpleListItem1, agent);

#pragma warning disable CS0618 // Type or member is obsolete
                Toast.MakeText(c, Html.FromHtml("<font color='green'>Parsing Data successful!</font>"), ToastLength.Short).Show();
#pragma warning restore CS0618 // Type or member is obsolete

            }
        }
        private int ParseData()
        {
            try
            {

                string[] list1 = jsonData.Split("\n");
                for (int x = 0; x < list1.Count(); x++)
                {
                    listing = list1[0];
                    listing1 = list1[1];
                    listing2 = list1[2];

                }



                JSONArray jsonArray = new JSONArray(listing);
                JSONObject jsonObj = null;



                for (int i = 0; i < jsonArray.Length(); i++)
                {
                    jsonObj = jsonArray.GetJSONObject(i);

                    String agentId = jsonObj.GetString("agent_id");
                    String agenName = jsonObj.GetString("agent_name");
                    DBAdapter db = new DBAdapter(c);
                        db.openDB();
                        db.addAgent(Convert.ToInt32(agentId), agenName);
                        db.closeDB();

                }


                JSONArray jsonArray1 = new JSONArray(listing1);
                JSONObject jsonObj1 = null;

                //custList.Add("Select Customer Name");

                for (int i = 0; i < jsonArray1.Length(); i++)
                {
                    jsonObj1 = jsonArray1.GetJSONObject(i);
                    String custID = jsonObj1.GetString("customer_id");
                    String custName = jsonObj1.GetString("customer_name");
                    DBAdapter db = new DBAdapter(c);
                    db.openDB();
                    db.addCust(Convert.ToInt32(custID), custName);
                    db.closeDB();
                }


                JSONArray jsonArray2 = new JSONArray(listing2);
                JSONObject jsonObj2 = null;

                for (int i = 0; i < jsonArray2.Length(); i++)
                {
                    jsonObj2 = jsonArray2.GetJSONObject(i);
                    String prodID = jsonObj2.GetString("product_id");
                    String prodName = jsonObj2.GetString("product_name");
                    DBAdapter db = new DBAdapter(c);
                    db.openDB();
                    db.addProd(Convert.ToInt32(prodID), prodName);
                    db.closeDB();

                }

                return 1;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
            }
            return 0;
        }
    }
}

Answers

Sign In or Register to comment.