私はXamarinとC#を使って基本的なAndroidアプリケーションを作成しています。 私は学習中です。C#のJsonファイルからリストビューを作成する
私がしようとしているのは、JSONファイルからいくつかのデータを抽出してListViewを読み込むことです。 私は、サーバーを呼び出すための非同期タスクとデータの解析と抽出のための非同期タスクの2つのメソッドを作成しました(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メソッドでそれらのオブジェクトのリストを作成する必要があります。彼らはListAdapaterを使用してそのデータをListViewに送ります。 – Jason