Cannot print the json message in listview using xa

2019-09-18 14:35发布

问题:

Using a xamarin cross platform development to i want print a json message from url and print in listview. I write code without error but with some mistakes. I will not work. For just a verfication output only i print the button in the output screen. I will shown but the listview was not print. Please recorrect my code.

    static ListView listview;
    static Button button;
    public MainPage()
    {
        listview = new ListView() { RowHeight = 40 };
        button = new Button() { Text = "search Again" };
        var stack = new StackLayout()
        {
            VerticalOptions = LayoutOptions.FillAndExpand,
            Children = { button, listview },
        };
        this.Content = stack;
        GetData();
    }
     async static void GetData()
    {
        WeatherReport res = new WeatherReport();
        try
        {
            string contents;
            string Url = String.Format("http://23.253.66.248:8080/icc/api/venue/search/?                lat=39.540544&lon=-104.866115&appkey=123Chesse&restName=MyMacChennai&organization=MyMacChennai");
            HttpClient hc = new HttpClient();
            contents = await hc.GetStringAsync(Url);
            res = JsonConvert.DeserializeObject<WeatherReport>(contents);
            listview.ItemsSource = res.list;
        }
        catch (System.Exception sysExc)
        {
            // Do something to log this error.
            throw;
        }
    }
 public class WeatherReport
 {
    public WeatherReport()
    {
        list = new List<WeatherReport>();
    }
    [JsonProperty(PropertyName = "cod")]
    public string cod { get; set; }
    [JsonProperty(PropertyName = "message")]
    public string message { get; set; }
    [JsonProperty(PropertyName = "cnt")]
    public int cnt { get; set; }
    [JsonProperty(PropertyName = "list")]
    public List<WeatherReport> list { get; set; }

回答1:

First, you shouldn't use async void except for eventhandlers, it is bad practice. Second, GetData() is an asynchronous method, however you are calling it synchronously in a constructor. I would advise redesigning this a bit so that it is async all the way through. You may be having issues since you are waiting for the code to finish before continuing on. Everything else in the code appears ok.

Here are some additional resources that might help with async/await. http://msdn.microsoft.com/en-us/magazine/jj991977.aspx, async/await - when to return a Task vs void?