Xamarin中的ListView使用RestApi [英] ListView in Xamarin using RestApi

查看:90
本文介绍了Xamarin中的ListView使用RestApi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以解决此错误.我想显示大量的API数据ListView.

例如API包含此类数据:

[{"id":"666","employee_name":"xyz","employee_salary":"123","employee_age":"23","profile_image":""}]

错误屏幕截图:

将JSON转换为c#之后创建的Class.cs

 public class employees
    {

        public string id { get; set; }
        public string employee_name { get; set; }
        public string employee_salary { get; set; }
        public string employee_age { get; set; }
        public string profile_image { get; set; }

    }

这是LoadData()用于调用API的XAML.cs文件

public async void LoadData()
        {
            var content = "";
            HttpClient client = new HttpClient();
            var RestURL = "MY API";  
            client.BaseAddress = new Uri(RestURL);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = await client.GetAsync(RestURL);
            content = await response.Content.ReadAsStringAsync();
            var Items = JsonConvert.DeserializeObject<List<employees>>(content);
            ListView1.ItemsSource = Items;
        }

这是Xamarin.Forms的XAML文件:

<StackLayout BackgroundColor="White">
        <ListView x:Name="ListView1" RowHeight="60">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Vertical" Padding="8,0,8,0">
                            <Label Text="{Binding id}" TextColor="#000" FontSize="14" LineBreakMode="TailTruncation" />
                            <Label Text="{Binding employee_name}" TextColor="#000" LineBreakMode="TailTruncation" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

解决方案

首先需要创建一个本地模型类:

public class TodoItem
{
    public string id { get; set; }

    public string employee_name { get; set; }

    public string employee_salary{ get; set; }

    public bool employee_age { get; set; }

    public bool profile_image { get; set; }
}

RestService中可以使用TodoItem:

public List<TodoItem> Items { get; private set; }

public async Task<List<TodoItem>> RefreshDataAsync ()
{
   Items = new List<TodoItem> ();
 // RestUrl = http://developer.xamarin.com:8081/api/todoitems
   var uri = new Uri (string.Format (Constants.RestUrl, string.Empty));
   try {
       var response = await client.GetAsync (uri);
       if (response.IsSuccessStatusCode) {
           var content = await response.Content.ReadAsStringAsync ();
           Items = JsonConvert.DeserializeObject <List<TodoItem>> (content);
        }
    } catch (Exception ex) {
           Debug.WriteLine (@"ERROR {0}", ex.Message);
    }
    return Items;
}

最后一个列表视图itemsource可以设置如下:

listView.ItemsSource = await RestService.RefreshDataAsync();

注意:这是您可以参考的官方示例

我能够解决此错误,我想显示大量API数据的列表视图

在列表视图中显示大数据,这是一个分页显示方法.获取API数据后,将其保存在本地CacheListData中.不要直接将其设置为listView.ItemsSource.您需要创建一个ItemListData从CacheListData添加数据.一次要显示的添加数据计数.当listview滚动到底部时,然后显示 Add More Swipe方法重新加载下一页数据. >

通常,解决方案是先将lagre数据缓存到本地,然后逐页获取数据以显示.

Error screenshot:

Class.cs which i made after converting JSON to c#

 public class employees
    {

        public string id { get; set; }
        public string employee_name { get; set; }
        public string employee_salary { get; set; }
        public string employee_age { get; set; }
        public string profile_image { get; set; }

    }

This is the XAML.cs file where LoadData() is using for calling API

public async void LoadData()
        {
            var content = "";
            HttpClient client = new HttpClient();
            var RestURL = "MY API";  
            client.BaseAddress = new Uri(RestURL);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = await client.GetAsync(RestURL);
            content = await response.Content.ReadAsStringAsync();
            var Items = JsonConvert.DeserializeObject<List<employees>>(content);
            ListView1.ItemsSource = Items;
        }

This is the XAML file of Xamarin.Forms:

<StackLayout BackgroundColor="White">
        <ListView x:Name="ListView1" RowHeight="60">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Vertical" Padding="8,0,8,0">
                            <Label Text="{Binding id}" TextColor="#000" FontSize="14" LineBreakMode="TailTruncation" />
                            <Label Text="{Binding employee_name}" TextColor="#000" LineBreakMode="TailTruncation" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

解决方案

First need to create a local model class :

public class TodoItem
{
    public string id { get; set; }

    public string employee_name { get; set; }

    public string employee_salary{ get; set; }

    public bool employee_age { get; set; }

    public bool profile_image { get; set; }
}

And in the RestService can use TodoItem:

public List<TodoItem> Items { get; private set; }

public async Task<List<TodoItem>> RefreshDataAsync ()
{
   Items = new List<TodoItem> ();
 // RestUrl = http://developer.xamarin.com:8081/api/todoitems
   var uri = new Uri (string.Format (Constants.RestUrl, string.Empty));
   try {
       var response = await client.GetAsync (uri);
       if (response.IsSuccessStatusCode) {
           var content = await response.Content.ReadAsStringAsync ();
           Items = JsonConvert.DeserializeObject <List<TodoItem>> (content);
        }
    } catch (Exception ex) {
           Debug.WriteLine (@"ERROR {0}", ex.Message);
    }
    return Items;
}

And last where your listview itemsource can set as follow:

listView.ItemsSource = await RestService.RefreshDataAsync();

Note: Here is a official sample you can refer to.

I'm enable to solve this error, i wanted to display listview of API data which is in large amount

Showing large data in listview,here is a paging show method.After getting API data, saving them in local CacheListData.Not directly set it to listView.ItemsSource .And you need create a ItemListData to add data from CacheListData.Which the count of added data according to you once want to show.When listview scroll to bottom ,then show Add More Swipe method to reload next page data.

Generally, Solution is to cache lagre data to local first.Then get data a little by page to show.Here is a solution link can refer to.

这篇关于Xamarin中的ListView使用RestApi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆