【发布时间】: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<Item>,这有点道理。例如:适配器如何知道要在列表中显示什么?只有项目的Id?或Content或者可能一起?我相信您需要的是自定义适配器。 -
非常感谢,我知道我必须了解有关自定义适配器的更多信息 - 自定义适配器将绑定数据是吗?
-
没错,自定义适配器用于将复杂数据绑定到列表视图。
-
@AndyRes 非常感谢,我想我很快就会找到解决方案。
标签: c# android http android-networking