how to fetch data from my web api using xamarin android?

JunCainJunCain ✭✭✭Member ✭✭✭
edited June 20 in Xamarin.Android

My Android App

Sycher.cs

 public class Syncher : AsyncTask
    {
        private Context c;``
        private string url, url1, url2, url3;
#pragma warning disable CS0618 // Type or member is obsolete
        private ProgressDialog Progress;
#pragma warning restore CS0618 // Type or member is obsolete

        public Syncher(Context c, string url, string url1, string url2, string url3)
        {
            this.c = c;
            this.url = url;
            this.url1 = url1;
            this.url2 = url2;
            this.url3 = url3;
        }

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

        protected override void OnPostExecute(Object result)
        {
            base.OnPostExecute(result);
            Progress.Dismiss();
            if(result == null)
            {
                Toast.MakeText(c, "Synchronizing failed!", ToastLength.Short).Show();
            }
            else
            {
                DataParser parser = new DataParser(c, result.ToString());
                parser.Execute();
            }
        }

        protected override Object DoInBackground(params Object[] @params)
        {
            return this.Retrieve() +

        }

        private string Retrieve()
        {
            HttpURLConnection con = Connector.Connect(url);
            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(url1);
            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(url2);
            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;
        }

        private string Retrieve3()
        {
            HttpURLConnection con3 = Connector.Connect3(url3);
            if (con3 == null)
            {
                return null;
            }
            try
            {
                Stream stream3 = new BufferedStream(con3.InputStream);
                BufferedReader bufferedReader3 = new BufferedReader(new InputStreamReader(stream3));
                string line3 = null;
                StringBuffer response3 = new StringBuffer();
                while ((line3 = bufferedReader3.ReadLine()) != null)
                {
                    response3.Append(line3 + "\n");
                }
                bufferedReader3.Close();
                stream3.Close();
                return response3.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return null;
        }
}

Connnector.cs

 public class Connector
    {
        public static HttpURLConnection Connect(String url)
        {
            try
            {
                URL address = new URL(url);
                HttpURLConnection con = (HttpURLConnection)address.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 url1)
        {
            try
            {
                URL address1 = new URL(url1);
                HttpURLConnection con1 = (HttpURLConnection)address1.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 url2)
        {
            try
            {
                URL address2 = new URL(url2);
                HttpURLConnection con2 = (HttpURLConnection)address2.OpenConnection();

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

        public static HttpURLConnection Connect3(String url3)
        {
            try
            {
                URL address3 = new URL(url3);
                HttpURLConnection con3 = (HttpURLConnection)address3.OpenConnection();

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

Answers

  • JunCainJunCain ✭✭✭ Member ✭✭✭

    MainActivity.cs

        public class MainActivity : AppCompatActivity, NavigationView.IOnNavigationItemSelectedListener
        {
            string url = "http://localhost:50402/api/agent?num=233445456";
            string url1 = "http://localhost:50402/api/customer?num=233445456";
            string url2 = "http://localhost:50402/api/product?num=233445456";
            string url3 = "http://localhost:50402/api/category?num=233445456";
            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
                SetContentView(Resource.Layout.activity_main);
                Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
                SetSupportActionBar(toolbar);
    
                DrawerLayout drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
                ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, Resource.String.navigation_drawer_open, Resource.String.navigation_drawer_close);
                drawer.AddDrawerListener(toggle);
                toggle.SyncState();
    
                NavigationView navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
                navigationView.SetNavigationItemSelectedListener(this);
            }
    
    
    
    
            public override bool OnCreateOptionsMenu(IMenu menu)
            {
                MenuInflater.Inflate(Resource.Menu.menu_main, menu);
                return true;
            }
    
            public override bool OnOptionsItemSelected(IMenuItem item)
            {
                int id = item.ItemId;
                if (id == Resource.Id.action_settings)
                {
                    //new Syncher(this, url, url1, url2, url3).Execute();
                    ConnectivityManager conMnger = (ConnectivityManager)GetSystemService(Context.ConnectivityService);
                    NetworkInfo netInfo = conMnger.ActiveNetworkInfo;
                    if (netInfo != null && netInfo.IsConnectedOrConnecting)
                    {
                        var sync = new Intent(this, typeof(SyncSplash));
                        sync.PutExtra("MyUrl", url + "|" + url1 + "|" + url2 + "|" + url3);
                        StartActivity(sync);
                        this.Finish();
                    }
                    else
                    {
    #pragma warning disable CS0618 // Type or member is obsolete
                        Toast.MakeText(Application.Context, Html.FromHtml("<font color='#f41f1f'>You are not connected to the internet, Please to any avialable wifi connection or activate your mobile data.</font>"), ToastLength.Long).Show();
    #pragma warning restore CS0618 // Type or member is obsolete
                    }
                }
    
                return base.OnOptionsItemSelected(item);
            }
    
            public bool OnNavigationItemSelected(IMenuItem item)
            {
                int id = item.ItemId;
    
                if (id == Resource.Id.nav_camera)
                {
                    StartActivity(typeof(ConfirmedOrders));
                }
                else if (id == Resource.Id.nav_gallery)
                {
                    StartActivity(typeof(UnconfirmedOrders));
                }
                else if (id == Resource.Id.nav_slideshow)
                {
                    StartActivity(typeof(SendOrders));
                }
                else if (id == Resource.Id.nav_manage)
                {
                    Toast.MakeText(this, "Sorry, but collection is under construction.", ToastLength.Long).Show();
                }
    
    
                 DrawerLayout drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
                drawer.CloseDrawer(GravityCompat.Start);
                return true;
            }
    
        }
    }
    

    SyncSplash.cs

        public class SyncSplash : Activity
        {
            ImageView imgView;
            AnimationDrawable animationD;
            public string myStr, str1, str2, str3, str4;
            public string url, url1, url2, url3;
            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
                SetContentView(Resource.Layout.SyncSplash);
                imgView = FindViewById<ImageView>(Resource.Id.animate);
                animationD = (AnimationDrawable)imgView.Drawable;
                animationD.Start();
                myStr = Intent.GetStringExtra("MyUrl") ?? "No Data";
                string[] str = myStr.Split("|");
                for(int i = 0; i < str.Count(); i++)
                {
                    url = str[0];
                    url1 = str[1];
                    url2 = str[2];
                    url3 = str[3];
                }
                if(url != "" && url1 != "" && url2 != "" && url3 != "")
                {
                    new Syncher(this, url, url1, url2, url3).Execute();
                }
            }
        }
    
  • JunCainJunCain ✭✭✭ Member ✭✭✭

    DataParser.cs

     public class DataParser : AsyncTask
        {
            Context c;
            private String jsonData;
            private string list, list1, list2, list3;
    #pragma warning disable CS0618 // Type or member is obsolete
            private ProgressDialog Progress;
    #pragma warning restore CS0618 // Type or member is obsolete
    
            public DataParser(Context c, String jsonData)
            {
                this.c = c;
                this.jsonData = jsonData;
            }
    
            protected override void OnPreExecute()
            {
                base.OnPreExecute();
    #pragma warning disable CS0618 // Type or member is obsolete
                Progress = new ProgressDialog(c);
    #pragma warning restore CS0618 // Type or member is obsolete
                Progress.SetTitle("Synchronizing");
                Progress.SetMessage("We're almost there!");
                Progress.SetCancelable(false);
                Progress.Show();
            }
    
            protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
            {
                return this.ParserData();
            }
    
            protected override void OnPostExecute(Java.Lang.Object result)
            {
                base.OnPostExecute(result);
                Progress.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
                    c.StartActivity(typeof(MainActivity));
                }
                else
                {
    #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
                    c.StartActivity(typeof(MainActivity));
                }
            }
    
            private int ParserData()
            {
                try
                {
                    string[] array = jsonData.Split("\n");
                    for (int x = 0; x < array.Count(); x++)
                    {
                        list = array[0];
                        list1 = array[1];
                        list2 = array[2];
                        list3 = array[3];
                    }
    
                    JSONArray jSONArray = new JSONArray(list);
                    JSONObject jSONObject = null;
    
                    for (int i = 0; i < jSONArray.Length(); i++)
                    {
                        jSONObject = jSONArray.GetJSONObject(i);
    
                        String agentId = jSONObject.GetString("agentId");
                        String agentName = jSONObject.GetString("agentName");
                        DBAdapter db = new DBAdapter(c);
                        db.openDB();
                        db.AddAgent(Convert.ToInt32(agentId), agentName);
                        db.closeDB();
                    }
    
                    JSONArray jSONArray1 = new JSONArray(list1);
                    JSONObject jSONObject1 = null;
    
                    for (int q = 0; q < jSONArray1.Length(); q++)
                    {
                        jSONObject1 = jSONArray1.GetJSONObject(q);
    
                        String custId = jSONObject1.GetString("custId");
                        String custName = jSONObject1.GetString("custName");
                        DBAdapter db = new DBAdapter(c);
                        db.openDB();
                        db.AddCustomer(Convert.ToInt32(custId), custName);
                        db.closeDB();
                    }
    
                    JSONArray jSONArray2 = new JSONArray(list2);
                    JSONObject jSONObject2 = null;
    
                    for (int z = 0; z < jSONArray2.Length(); z++)
                    {
                        jSONObject2 = jSONArray2.GetJSONObject(z);
    
                        String prodId = jSONObject2.GetString("productId");
                        String prodName = jSONObject2.GetString("prodName");
                        DBAdapter db = new DBAdapter(c);
                        db.openDB();
                        db.AddProduct(Convert.ToInt32(prodId), prodName);
                        db.closeDB();
                    }
    
                    JSONArray jSONArray3 = new JSONArray(list3);
                    JSONObject jSONObject3 = null;
    
                    for (int n = 0; n < jSONArray3.Length(); n++)
                    {
                        jSONObject3 = jSONArray3.GetJSONObject(n);
    
                        String catId = jSONObject3.GetString("catId");
                        String catName = jSONObject3.GetString("catName");
                        DBAdapter db = new DBAdapter(c);
                        db.openDB();
                        db.AddProdCat(Convert.ToInt32(catId), catName);
                        db.closeDB();
                    }
                    return 1;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                return 0;
            }
        }
    
  • JunCainJunCain ✭✭✭ Member ✭✭✭

    My web api

    CategoryController.cs

      public class CategoryController : ApiController
        {
            List<CategoryModel> categories = new List<CategoryModel>();
            public CategoryController()
            {
                var data = ViewCategory();
                if (data.Rows.Count > 0)
                {
                    categories = (from DataRow dr in data.Rows
                                  select new CategoryModel()
                                  {
                                      catId = Convert.ToInt32(dr["catId"]),
                                      catName = Convert.ToString(dr["catName"]),
                                      agentContact = Convert.ToString(dr["agentContact"])
                                  }).ToList();
                }
            }
            // GET: api/Category
            public List<CategoryModel> Get()
            {
                return categories;
            }
    
            // GET: api/Category/5
            public CategoryModel Get(string num)
            {
                return categories.Where(x => x.agentContact.Equals(num)).FirstOrDefault();
            }
    }
    

    AgentController.cs

     public class AgentController : ApiController
        {
            List<AgentModel> agents = new List<AgentModel>();
            public AgentController()
            {
    
                var data = ViewAgent();
                if (data.Rows.Count > 0)
                {
                    agents = (from DataRow dr in data.Rows
                              select new AgentModel()
                              {
                                  agentId = Convert.ToInt32(dr["agentId"]),
                                  agentName = Convert.ToString(dr["agentName"]),
                                  agentAddress = Convert.ToString(dr["agentAddress"]),
                                  agentContact = Convert.ToString(dr["agentContact"]),
                                  agentStatus = Convert.ToString(dr["agentStatus"]),
                                  catId = Convert.ToInt32(dr["catId"])
                              }).ToList();
    
                }
            }
    
            // GET: api/Agent
            public List<AgentModel> Get()
            {
                return agents;
            }
            // GET: api/Agent/5
            public AgentModel Get(string num)
            {
                return agents.Where(e => e.agentContact.Equals(num)).FirstOrDefault();
            }
    }
    

    CustomerController.cs

     public class CustomerController : ApiController
        {
            List<CustomerModel> customers = new List<CustomerModel>();
            public CustomerController()
            {
    
                var _data = ViewCustomer();
                if (_data.Rows.Count > 0)
                {
                    customers = (from DataRow _dr in _data.Rows
                                 select new CustomerModel()
                                 {
                                     custId = Convert.ToInt32(_dr["custId"]),
                                     custName = Convert.ToString(_dr["custName"]),
                                     custAddress = Convert.ToString(_dr["custAddress"]),
                                     custContact = Convert.ToString(_dr["custContact"]),
                                     custStatus = Convert.ToString(_dr["custStatus"]),
                                     agentId = Convert.ToInt32(_dr["agentId"]),
                                     agentContact = Convert.ToString(_dr["agentContact"])
                                 }).ToList();
                }
            }
    
            // GET: api/Customer
            public List<CustomerModel> Get()
            {
                return customers;
            }
    
            // GET: api/Customer/5
            public List<CustomerModel> Get(string num)
            {
                return customers.Where(x => x.agentContact.Equals(num)).ToList();
            }
    }
    

    ProductController.cs

     public class ProductController : ApiController
        {
            List<ProductModel> products = new List<ProductModel>();
            public ProductController()
            {
                var data = ViewProduct();
                if(data.Rows.Count > 0)
                {
                    products = (from DataRow dr in data.Rows
                                select new ProductModel()
                                {
                                    prodId = Convert.ToInt32(dr["productId"]),
                                    prodName = Convert.ToString(dr["prodName"]),
                                    prodStatus = Convert.ToString(dr["prodStatus"]),
                                    catId = Convert.ToInt32(dr["catId"]),
                                    agentContact = Convert.ToString(dr["agentContact"])
    
                                }).ToList();
                }
            }
            // GET: api/Product
            public List<ProductModel> Get()
            {
                return products;
            }
    
            // GET: api/Product/5
            public List<ProductModel> Get(string num)
            {
                return products.Where(x => x.agentContact.Equals(num)).ToList();
            }
    }
    
  • JunCainJunCain ✭✭✭ Member ✭✭✭

    Screenshot using Postman..




  • JarvanJarvan Xamurai Member, Xamarin Team Xamurai
    edited June 20

    warning disable CS0618 // Type or member is obsolete

    To fix the CS0618 error you will need to use the new property/method that has replaced the obsolete property/method.

Sign In or Register to comment.