将xson数组绑定到xamarin android中的listview时出错

时间:2016-03-24 11:35:15

标签: c# android listview xamarin

我正在尝试将JSON数组响应绑定到listview,但我在activity.cs类中遇到了一些错误。我做错了什么。请帮助我,我是android的新手。

WCF服务响应

[{
    "Region":"String content",
    "ID":21,
    "Msg":"String content",
    "Status":214
}]

regionModel.cs

public class regionModel
    {

        public int ID { get; set; }
        public string Region { get; set; }
        public string Msg { get; set; }
        public int Status { get; set; }

    }

Activity.cs

 List<regionTable> regionItems = new List<regionTable>();
      protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.HomeScreen);
            listView = FindViewById<ListView>(Resource.Id.List);


                   var client = new RestClient("http://azurewebsites.net/");
            var request = new RestRequest("RegionService/GetRegions", Method.POST);
            request.RequestFormat = DataFormat.Json;
            regionItems = client.Execute<List<regionTable>>(request).Data;


            JSONArray JA = new JSONArray(regionItems);

        for (int i = 0; i < JA.Length(); i++)
        {
            try
            {
                JSONObject jsonObject = JA.GetJSONObject(i);
                regionItems.Add(jsonObject.GetString("ID"));    
            }
            catch (JSONException e)
            {
               // e.printStackTrace();
            }
        }


            listView.Adapter = new HomeScreenAdapter(this,regionItems );

HomeScreenAdapter。 CS

public class HomeScreenAdapter : BaseAdapter<TableItem> {
    List<TableItem> items;
    Activity context;
    public HomeScreenAdapter(Activity context, List<TableItem> items)
        : base()
    {
        this.context = context;
        this.items = items;
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override TableItem this[int position]
    {
        get { return items[position]; }
    }
    public override int Count
    {
        get { return items.Count; }
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        var item = items[position];

        View view = convertView;
        if (view == null) // no view to re-use, create new
            view = context.LayoutInflater.Inflate(Resource.Layout.CustomView, null);
        view.FindViewById<TextView>(Resource.Id.Text1).Text = item.Region;

        return view;
    }
  }
}

1 个答案:

答案 0 :(得分:0)

请阅读文档:JSONArray.Length()(注意资本“L”)和JSONArray.GetJSONObject()(资本“G”)和JSONObject.GetString()(资本“G”)。

Xamarin倾向于遵循C#命名约定,而不是Android使用的Java约定。