【问题标题】:Get Data with HTTP request Android Xamarin C#使用 HTTP 请求获取数据 Android Xamarin C#
【发布时间】:2016-12-30 11:19:13
【问题描述】:

朋友们好,这是我的第一个 Android 应用程序,我正在尝试从 wep api 获取数据并显示在列表视图中。 现在我先说一下我的步骤,我做了一个类,这个类通过http请求获取数据。

class WebRequests
{
    public static List<Item> GetAllItems()
    {
        List<Item> lp = new List<Item>();
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        try
        {
            HttpResponseMessage response = client.GetAsync("https://MyUrlToApi/api/myitems").Result;
            if (response.IsSuccessStatusCode)
            {
                lp = JsonConvert.DeserializeObject<Item[]>(response.Content.ReadAsStringAsync().Result).ToList();
            }
        }
        catch
        {

        }
        return lp;
    }

我已经制作了一个带有项目属性的模型:

public class Item
{
    public string Id { get; set; }
    public string Content { get; set; }

}

我的主要活动是:

[Activity(Label = "GetDataFromWebApiAndroid", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    ListView listView;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);
        var result = WebRequests.GetAllItems();

        listView = FindViewById<ListView>(Resource.Id.listAll);
        listView.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, result);
        listView.ChoiceMode = ChoiceMode.None;
    }
}

所以当我运行我的应用程序时,我的列表视图会显示:

但我的数据是:

谁能帮我解释一下我做错了什么。

【问题讨论】:

  • 我从未使用过 Xamarin 或 C#,但查看屏幕截图和代码,ArrayAdapter 似乎无法正确呈现给定的对象列表:List&lt;Item&gt;,这有点道理。例如:适配器如何知道要在列表中显示什么?只有项目的Id?或Content 或者可能一起?我相信您需要的是自定义适配器。
  • 非常感谢,我知道我必须了解有关自定义适配器的更多信息 - 自定义适配器将绑定数据是吗?
  • 没错,自定义适配器用于将复杂数据绑定到列表视图。
  • @AndyRes 非常感谢,我想我很快就会找到解决方案。

标签: c# android http android-networking


【解决方案1】:

我找到了解决方案,也许这会对新的 Android 开发人员有所帮助。特别感谢 AndyRes 正确的方法。 所以为了正确显示数据,我应该创建自定义适配器来绑定数据。 首先必须创建Item类,我叫它模型:

public class Item
{
    public string Id { get; set; }
    public string Content { get; set; }

    public Item(string Id, string Content)
    {
        this.Id = Id;
        this.Content = Content;
    }
}

现在自定义适配器:

class ItemListAdapter : BaseAdapter<Item>
{
    Activity context;
    public List<Item> listItems { get; set; }
    public ItemListAdapter(Activity context, List<Item> Items) : base()
    {
        this.context = context;
        this.listItems = Items;
    }
    public override Item this[int position]
    {
        get
        {
            return this.listItems[position];
        }
    }

    public override int Count
    {
        get
        {
            return this.listItems.Count;
        }
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        Item item = listItems[position];
        View view = convertView;
        if (convertView == null || !(convertView is LinearLayout))

            view = context.LayoutInflater.Inflate(Resource.Layout.Itemlayout, parent, false);
        TextView itemId = view.FindViewById(Resource.Id.textItemId) as TextView;
        TextView itemContent = view.FindViewById(Resource.Id.textItemContent) as TextView;

        itemId.SetText(item.Id, TextView.BufferType.Normal);
        itemContent.SetText(item.Content, TextView.BufferType.Normal);

        return view;

    }
}

最后在 Activity 中进行更改:

[Activity(Label = "CustomAdapterAndroidApp", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    private ListView listItems;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);
        listItems = FindViewById<ListView>(Resource.Id.listViewItems);
        PopulateItemsList();
    }

    private void PopulateItemsList()
    {
        listItems.Adapter = new ItemListAdapter(
           this, new List<Item>
            {
                new Item("222", "First Sample"),
                new Item("111", "Второй пример"),
                new Item("333", "მესამე მანალითი")
            }); 

    }

不要忘记创建特殊的布局来显示每个项目:

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
<TextView
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textItemId" />
<TextView   
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textItemContent" />
</LinearLayout>

并确保在主布局中放置列表。 再次感谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多