隐藏

Xamarin android 调用Web Api(ListView使用远程数据)

发布:2019/4/14 11:18:21作者:管理员 来源:本站 浏览次数:897

Xamarin android 调用Web Api(ListView使用远程数据)

xamarin android如何调用sqlserver 数据库呢(或者其他的),很多新手都会有这个疑问。xamarin android调用远程数据主要有两种方式:

    在Android中保存数据或调用数据库可以利用SQLite,android中提供了几个类来管理SQLite数据库,对数据进行增删改查
    直接调用Asp.net Web API对数据进行增删改查

这两种方式到底选择哪一种方式好一点呢?哪一种方式好不好我不敢确定,市场上大部分app都是调用api来clud的。当然我也推荐大家使用web api来调用远程数据,至少目前来看我们公司都是使用web api来做的。好吧废话不多说,下面就是ListView来调用web api执行增删改查的例子。

先看一下效果图:


这个示例我还是拿之前的listview入门的例子做, xamarin android listview的用法,数据是直接调用远程的web api中的数据。主要实现步骤

    新建一个web api的项目,写好要用到的方法。
    在MainActivity.cs中发送请求并将相应的json字符串序列化成List集合

 web api中的 NewsControl.cs

    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Web.Http;
    using WebApi10_9.Models;
    namespace WebApi10_9.Controllers
    {
        public class NewsController : ApiController
        {
            List<News> list = new List<News>() {
                  new News (1001,"加内特的历史地位能在NBA排第几,超越德国战车?",1200),
                    new News (1002,"盘点新赛季最期待的十场比赛,无湖人比赛?",560),
                    new News (1003,"库里新赛季铁定无缘常规赛MVP",158200),
                    new News (1004,"我服,库里,杜兰特,汤普森谁才是出手的最佳选择",900),
                    new News (1005,"易建联的出场时间你能猜出来吗,大概多少",960),
                      new News (1006,"卡戴珊三姐妹睡多少男人",960),
                      new News(1007,"科比退役后湖人到底失去多少中国的粉丝",4986),
                      new News(1008,"科比退役湖人签中国篮球当家背后隐藏了多少阴谋",65987)
           };
            public IEnumerable<News> GetAllNews()
            {
                return list;
            }
            [HttpGet]
            public List<News> Remove(int id)
            {
                var item = list.FirstOrDefault(p => p.Id == id);
                if (item == null)
                   throw new HttpResponseException(HttpStatusCode.NotFound);
                list.Remove(item);
                return list;
            }
        }
    }


MainActivity.cs

    using Android.App;
    using Android.Content;
    using Android.Views;
    using Android.Widget;
    using Android.OS;
    using System.Collections.Generic;
    using DrawerLayout.Adapter;
    using Newtonsoft.Json;
    using System.Net;
    using System.Text;
    using System.IO;
    namespace DrawerLayout
    {
        [Activity(Label = "ListViewDemo", MainLauncher = true, Icon = "@drawable/icon")]
        public class MainActivity : Activity
        {
            int count = 1;
            private List<News> data;
            private Context context;
            private NewsAdapter adapter;
            private ListView lv_test;
            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);
                SetContentView(Resource.Layout.Main);
                //data = new List<News>() {
                //    new News (1001,"加内特的历史地位能在NBA排第几,超越德国战车?",1200),
                //    new News (1002,"盘点新赛季最期待的十场比赛,无湖人比赛?",560),
                //    new News (1003,"库里新赛季铁定无缘常规赛MVP",158200),
                //    new News (1004,"我服,库里,杜兰特,汤普森谁才是出手的最佳选择",900),
                //    new News (1005,"易建联的出场时间你能猜出来吗,大概多少",960),
                //      new News (1006,"卡戴珊三姐妹睡多少男人",960),
                //      new News(1007,"科比退役后湖人到底失去多少中国的粉丝",4986),
                //      new News(1008,"科比退役湖人签中国篮球当家背后隐藏了多少阴谋",65987)
                //};
                string url = "http://192.168.1.172:100/api/news";
                string content = AccessData.GetRouteData(url ); //接收到响应的json 字符串
                List<News> list = JsonConvert.DeserializeObject<List<News>>(content); //已经获取到远程数据的List<News>和之前的本地data就是一样的了。
                adapter = new NewsAdapter(list,this);
                lv_test = FindViewById<ListView>(Resource.Id.lv_test);
                View lv_header = LayoutInflater.Inflate(Resource.Layout.lv_header, null);
                lv_test.AddHeaderView(lv_header);
                lv_test.Adapter = adapter;
            }
            public class AccessData
            {
                public static string GetRouteData (string url)
                {
                    //构建请求
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.ContentType = "text/json;chartset=UTF-8";
                    //request.UserAgent = "";
                    request.Method = "Get";
                    //接收响应
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream stream = response.GetResponseStream();
                    StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
                    string retString = streamReader.ReadToEnd();
                    return retString;
                }
            }
        }
    }

当然还有一个单击删除的事件还没有写,这个在NewsAdapter.cs里面写。

            public override View GetView(int position, View convertView, ViewGroup parent)
            {
                convertView = LayoutInflater.From(context).Inflate(Resource.Layout.lv_test,parent,false);
                ViewHolder holder = null;
                if (convertView != null)
                {
                    holder = new ViewHolder();
                    holder.btn = convertView.FindViewById<Button>(Resource.Id.btn_delete);
                    holder.title = convertView.FindViewById<TextView>(Resource.Id.tv_title);
                    holder.pv = convertView.FindViewById<TextView>(Resource.Id.tv_pv);
                }
                else
                {
                    convertView.Tag = holder;
                }
                holder.pv.Text = data[position].Pv.ToString();
                holder.title.Text = data[position].Title;
                holder.btn.Click += (s, e) => DeleteClick(data[position].Id,position);
                return convertView;
            }
            public void DeleteClick(int id,int position)
            {
                string url = "http://192.168.1.172:100/api/news/"+id;
                string content = AccessData.GetRouteData(url); //已经接收到响应的json 字符串
                Toast.MakeText(context,data[position].Title+"删除成功",ToastLength.Short).Show();
                List<News> list = JsonConvert.DeserializeObject<List<News>>(content);
                data = list;
                NotifyDataSetChanged();
            }
        }
        public class ViewHolder:Java.Lang.Object
        {
            public TextView title;
            public TextView pv;
            public Button btn;
        }


好了,这样就大功告成了。那么问题来了,上面发送http请求,然后又接收响应再序列化,这还仅仅是一个简单的例子,要是复杂实用一点的话,要写很多很多代码,这里我推荐一个非常好的第三方组件,http请求响应第三方组件RestSharp用的非常广泛。用法很简单,看完这篇大概你就懂了RestSharp的10分钟入门实例。我为什么推荐大家使用这个第三方组件呢,因为本屌所在公司也是用这个的,好东西,就是要懂得分享,当然那种直接利用HttpWebRequest ,HttpWebResonse对象来获取文件流再序列化成List集合的原始方法肯定是要知道的。直接上代码,结果还是一样的。哦,先先Nuget下载RestSharp 才能引用。


       protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);
                SetContentView(Resource.Layout.Main);
                string url = "http://192.168.1.172:100/api/news";
               <span style="color:#ff0000;"> var client = new RestClient(url);//创建客户端请求
                var request = new RestRequest();
                //RestResponse response = (RestResponse)client.Execute(request);
                //string responseStr = response.Content; 这两句获取json字符串,下面两句获取集合也很简洁
                IRestResponse<List<News>> responseList = client.Get<List<News>>(request);
                List<News> list = responseList.Data;</span>
                //string content = AccessData.GetRouteData(url ); //接收到响应的json 字符串
                //List<News> list = JsonConvert.DeserializeObject<List<News>>(content); //已经获取到远程数据的List<News>和之前的本地data就是一样的了。
                adapter = new NewsAdapter(list,this);
                lv_test = FindViewById<ListView>(Resource.Id.lv_test);
                View lv_header = LayoutInflater.Inflate(Resource.Layout.lv_header, null);
                lv_test.AddHeaderView(lv_header);
                lv_test.Adapter = adapter;
            }


删除也是差不多的,所以不贴了,只需要这几句就可以了实现发送请求接收响应了。大力推荐使用RestSharp。