【发布时间】:2017-05-18 03:07:33
【问题描述】:
我正在使用 Xamarin 和 C# 创建一些基本的 Android 应用程序。 我正在学习中。
我想要做的是用从 JSON 文件中提取的一些数据填充 ListView。 我做了两种方法,一种是调用服务器的异步任务,另一种是解析和提取数据(http://mysafeinfo.com/api/data?list=englishmonarchs&format=json)。
我现在的问题是我不知道如何为列表视图提供这些数据。
感谢您的宝贵时间。
namespace App4
{
[Activity(Label = "App4", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
//Declare a Cancellation Token Source
CancellationTokenSource cts;
Button startbutton;
Button stopbutton;
TextView textView0;
ListView listView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
startbutton = FindViewById<Button>
(Resource.Id.startbutton);
stopbutton = FindViewById<Button>
(Resource.Id.stopbutton);
textView0 = FindViewById<TextView>
(Resource.Id.textView0);
listView = FindViewById<ListView>
(Resource.Id.listView);
//BASIC ASYNC START TASK
// click the startbutton to start the process
startbutton.Click += async (sender, e) =>
{
// Instantiate the CancellationTokenSource
cts = new CancellationTokenSource();
try
{
// **** GET ****
await Task.Run(() => LoadDataAsync(cts.Token));
}
catch (TaskCanceledException)
{
textView0.Text = " Download deleted ";
}
catch (Exception)
{
textView0.Text = "Generic Error";
}
// ***Set the CancellationTokenSource to null when the download is complete.
cts = null;
};
//STOP BUTTON
stopbutton.Click += (sender, e) =>
{
if (cts != null)
{
cts.Cancel();
}
};
}
//THIS METHOD LOAD JSON DATA FROM AN URL AND RETURN A STRING
public static async Task<string> LoadDataAsync(CancellationToken ct)
{
// Call the server and take the file
var client = new HttpClient();
client.MaxResponseContentBufferSize = 1024 * 1024; //read up to 1MB of data
await Task.Delay(250);//Delay the task for deleting purpose
var response = await client.GetAsync(new Uri("http://mysafeinfo.com/api/data?list=englishmonarchs&format=json"), ct);
var result = await response.Content.ReadAsStringAsync();
return result;
}
//THIS METHOD GET THE JSON DATA FROM THE STRING
private static void GetData(string result)
{
// Parse the Json file.
JArray file = JArray.Parse(result);
foreach (var item in file.Children<JObject>())
{
string name = (string)item.SelectToken("nm");
string city = (string)item.SelectToken("cty");
string house = (string)item.SelectToken("hse");
string years = (string)item.SelectToken("yrs");
}
}
}
}
【问题讨论】:
-
您需要创建一个域对象,该对象具有每个数据元素(名称、城市等)的属性,然后在您的 GetData 方法中创建这些对象的列表。他们使用 ListAdapter 将该数据提供给您的 ListView