Home > Software design >  How to display the variable declared in a class
How to display the variable declared in a class

Time:04-02

I created a class called Weather as below:

public class Weather
{
    public string WeatherName { get; set; }
    public int WeatherId { get; set; }
}

And then, I would like to get the data from an URL and display the data I've got.

public partial class HomePage : ContentPage
{
    
    public HomePage()
    {
        InitializeComponent();
        GetWeather();
    }

    async public void GetWeather()
    {
        string url = "the URL....";

        var handler = new HttpClientHandler();
        HttpClient client = new HttpClient(handler);
        string result = await client.GetStringAsync(url);

        var resultObject = JObject.Parse(result);
        int WeatherId = (int)resultObject["icon"][0]; //get the "icon" data from the JSON file
        Weather weather = new Weather();
        weather.WeatherId = WeatherId;
        switch (WeatherId)
        {
            //setting the WeatherName according to the WeatherId...
        }
    }
    
}

I would like to display the WeatherId and the WeatherName, but I have no idea how to do that. Please give me a simple solution as I may not understand some difficult codes.

CodePudding user response:

in your page, add some UI elements to display the data

// these go inside of the page's Content tags
<StackLayout>
  <Label x:Name="WeatherIDLabel" />
  <Label x:Name="WeatherNameLabel" />
</StackLayout>

then in your code when you retrieve the data

WeatherIDLabel.Text = weather.WeatherId;
WeatherNameLabel.Text = weather.WeatherName;

there are thousands of excellent tutorials, videos, sample apps, etc that illustrate how to build an app from scratch. I suggest you take the time to walk through some of them

  • Related