Retrieving Weather Info In Xamarin.Forms Application For Android And UWP

Weather Information is important for planning our day-to-day activities. Reading this article, you will learn to retrieve weather details using API key from openweathermap.org in Xamarin.Forms application, for Android and Universal Windows Platform.

The following important tools are required for developing the UWP.

  1. Windows 10 (Recommended)
  2. Visual Studio 2017 Community (https://www.visualstudio.com/downloads/ )
  3. Get a free Weather API key from http://openweathermap.org/appid

Now, we can discuss step by step app development.

Step 1

Open Visual Studio 2017 and go to Start -> New Project -> Cross-Platform (under Visual C#) -> Cross Platform App (Xamarin) -> Give the suitable name for your app (XamWeather) -> OK.

Step 2

Select the Cross-Platform template as a Blank APP. Set UI Technology as Forms and Sharing as PCL. Visual Studio creates 4 projects (Portable, Droid, iOS, UWP) and displays Getting Started.XamarinPage.

Step 3

For User View, in MainPage.Xaml Page, add the label control for title inside StackLayout.

  1. <StackLayout HorizontalOptions="Center" VerticalOptions="Center">  
  2.    <Label Text="Weather App Using Xamarin Forms" FontSize="20" VerticalOptions="Center" HorizontalOptions="Center"/>  
  3. </StackLayout>  

Add Label, Entry, and button controls for getting PINCODE from the user.

  1. <StackLayout HorizontalOptions="Start" Margin="10,10,0,0" WidthRequest="400">  
  2.     <Label Text="Enter Your PIN Code" FontAttributes="Bold" TextColor="White" Margin="10" x:Name="lblSearch" />  
  3.     <Label Text="PIN Code" TextColor="White" Margin="10" x:Name="lblPinCode" />  
  4.     <StackLayout Orientation="Horizontal">  
  5.         <Entry WidthRequest="100" x:Name="entPinCode" />  
  6.         <Button Text="Get Weather Info" x:Name="btnGetWeather" /> </StackLayout>  
  7. </StackLayout>  

Add the Label Controls for displaying Location, Temperature, Sunrise, Sunset, Wind Speed, and Humidity.

  1. <StackLayout VerticalOptions="StartAndExpand">  
  2.     <Label Text="Location" TextColor="Black" FontSize="14" />  
  3.     <Label Text="" Margin="10,0,0,10" x:Name="txtLocation" />  
  4.     <Label Text="Temperature" TextColor="Black" FontSize="14" />  
  5.     <Label Text="" Margin="10,0,0,10" x:Name="txtTemperature" />  
  6.     <Label Text="Sunrise" TextColor="Black" FontSize="14" />  
  7.     <Label Text="" Margin="10,0,0,10" x:Name="txtSunrise" />  
  8.     <Label Text="Sunset" TextColor="Black" FontSize="14" />  
  9.     <Label Text="" Margin="10,0,0,10" x:Name="txtSunset" />  
  10.     <Label Text="Wind Speed" TextColor="Black" FontSize="14" />  
  11.     <Label Text="" Margin="10,0,0,10" x:Name="txtWind" />  
  12.     <Label Text="Humidity" TextColor="Black" FontSize="14" />  
  13.     <Label Text="" Margin="10,0,0,10" x:Name="txtHumidity" />   
  14. </StackLayout>  

Step 4

For performing the HTTP request and response, add the Newton.json file's reference.

Right-click the Solution(XamWeather)->Manage NuGet packages for Solution.

Browse and install the reference.

Step 5

Add the following class code for data binding (store the Weather details) in MainPage.Xaml.cs.

  1. public class Weather {  
  2.     public string Title {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Temperature {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public string Wind {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public string Humidity {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public string Visibility {  
  19.         get;  
  20.         set;  
  21.     }  
  22.     public string Sunrise {  
  23.         get;  
  24.         set;  
  25.     }  
  26.     public string Sunset {  
  27.         get;  
  28.         set;  
  29.     }  
  30.     public Weather() {  
  31.         this.Title = " ";  
  32.         this.Temperature = " ";  
  33.         this.Wind = " ";  
  34.         this.Humidity = " ";  
  35.         this.Visibility = " ";  
  36.         this.Sunrise = " ";  
  37.         this.Sunset = " ";  
  38.     }  
  39. }  

Step 6

Add the following namespace and code for btnGetWeather_Click (send the PIN code detail and retrive the information) Event method.

  1. using Newtonsoft.Json;  
  2. using System.Net.Http;  
  3. private async void btnGetWeather_Click(object sender, EventArgs e) {  
  4.     if (!String.IsNullOrEmpty(entPinCode.Text)) {  
  5.         Weather weather = await GetWeather(entPinCode.Text);  
  6.         if (weather != null) {  
  7.             txtLocation.Text = weather.Title;  
  8.             txtTemperature.Text = weather.Temperature;  
  9.             txtWind.Text = weather.Wind;  
  10.             txtHumidity.Text = weather.Humidity;  
  11.             txtSunrise.Text = weather.Sunrise;  
  12.             txtSunset.Text = weather.Sunset;  
  13.             btnGetWeather.Text = "Search Again";  
  14.         }  
  15.     }  
  16. }  
  17. public static async Task < Weather > GetWeather(string pinCode) {  
  18.     string key = "Your Key";  
  19.     string queryString = "http://api.openweathermap.org/data/2.5/weather?zip=" + pinCode + ",in&appid=" + key + "&units=imperial";  
  20.     if (key != " Your Key ") {  
  21.         throw new ArgumentException("Get you API key from openweathermap.org/appid and assign it in the 'key' variable.");  
  22.     }  
  23.     dynamic results = await getDataFromService(queryString).ConfigureAwait(false);  
  24.     if (results["weather"] != null) {  
  25.         Weather weather = new Weather();  
  26.         weather.Title = (string) results["name"];  
  27.         weather.Temperature = (string) results["main"]["temp"] + " F";  
  28.         DateTime time = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);  
  29.         DateTime sunrise = time.AddSeconds((double) results["sys"]["sunrise"]);  
  30.         DateTime sunset = time.AddSeconds((double) results["sys"]["sunset"]);  
  31.         weather.Sunrise = sunrise.ToString() + " UTC";  
  32.         weather.Sunset = sunset.ToString() + " UTC";  
  33.         weather.Wind = (string) results["wind"]["speed"] + " mph";  
  34.         weather.Humidity = (string) results["main"]["humidity"] + " %";  
  35.         return weather;  
  36.     } else {  
  37.         return null;  
  38.     }  
  39. }  
  40. public static async Task < dynamic > getDataFromService(string pQueryString) {  
  41.     HttpClient client = new HttpClient();  
  42.     var response = await client.GetAsync(pQueryString);  
  43.     dynamic data = null;  
  44.     if (response != null) {  
  45.         string json = response.Content.ReadAsStringAsync().Result;  
  46.         data = JsonConvert.DeserializeObject(json);  
  47.     }  
  48.     return data;  
  49. }  

Step 7

Deploy your app to Android Emulator and Local Machine (UWP). The output of the XamWeather App is shown below.



Summary

Now, you have successfully retrieved Weather details using API key from openweathermap.org in Xamarin.Forms application under cross-platform application development.