Hi,
I have a simple app and trying ot run it on android but having a problem..
The OnAppearing is not getting invoked at all when startup.. but when I navigate from the app then come back that time it will run.. or when I keep the app active and turn of the device power (power button) and turn it on again..
What could be the reason for this?
Here is my code:
App.xaml.cs:
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Microsoft.AppCenter;
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter.Crashes;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace Samana
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage())
{
BarBackgroundColor = Color.White,
BarTextColor = Color.Black
};
}
protected override void OnStart()
{
// Handle when your app starts
AppCenter.Start("android=c869509f-27c9-4f76-86a6-2b17ee3904a4; ios=948a8946-2a7a-4185-a059-892c12f50c0d",
typeof(Analytics), typeof(Crashes));
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
MainPage.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:FFImageLoading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
xmlns:FFTransformations="clr-namespace:FFImageLoading.Transformations;assembly=FFImageLoading.Transformations"
xmlns:SyncfusionBusyIndicator="clr-namespace:Syncfusion.SfBusyIndicator.XForms;assembly=Syncfusion.SfBusyIndicator.XForms"
xmlns:local="clr-namespace:Samana"
x:Class="Samana.MainPage">
<Grid Padding="0" Margin="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" HorizontalOptions="Start" Text="settings" />
<StackLayout Grid.Column="1">
<Label x:Name="LabelPlaceName" HorizontalOptions="Center" Text="city" />
<Label x:Name="LabelLocalTime" HorizontalOptions="Center" Text="time" />
</StackLayout>
<Label Grid.Column="2" HorizontalOptions="End" Text="plus" />
</Grid>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackLayout Grid.Column="0" HorizontalOptions="Center" VerticalOptions="CenterAndExpand">
<Label x:Name="LabelTemprature" HorizontalOptions="Center" FontSize="Large" />
<Label x:Name="LabelDescription" HorizontalOptions="Center" FontSize="Medium" />
</StackLayout>
<FFImageLoading:CachedImage x:Name="ImageWeatherIcon" Grid.Column="1" WidthRequest="150" HeightRequest="150" DownsampleToViewSize="true" FadeAnimationForCachedImages="True" FadeAnimationDuration="100">
</FFImageLoading:CachedImage>
</Grid>
<ScrollView Grid.Row="2">
<StackLayout>
<Label Text="Name:" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
<Label x:Name="LabelName" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
<Button Text="Get" Clicked="Button_Clicked" />
</StackLayout>
</ScrollView>
</Grid>
</ContentPage>
MainPage.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Net;
using System.Net.Http;
using System.Web;
using Newtonsoft.Json;
using System.Xml;
using Xamarin.Essentials;
using Microsoft.AppCenter;
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter.Crashes;
using Newtonsoft.Json.Linq;
namespace Samana
{
public partial class MainPage : ContentPage
{
private string api_key = "1f02b0d8e182b5c9e9951627aa372b23";
public MainPage()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
}
protected override async void OnAppearing()
{
base.OnAppearing();
var location_data = await GetLocation();
await DisplayAlert("feature_name", location_data.feature_name, "OK");
await DisplayAlert("admin_area", location_data.admin_area, "OK");
await DisplayAlert("locality", location_data.locality, "OK");
await DisplayAlert("thoroughfare", location_data.thoroughfare, "OK");
string url = "https://samples.openweathermap.org/data/2.5/weather?lat=" + location_data.latitude + "&lon=" + location_data.longitude + "&appid=" + api_key;
using (WebClient web_client = new WebClient())
{
var json = web_client.DownloadString(url);
var result = JsonConvert.DeserializeObject<WeatherInfo.Root>(json);
WeatherInfo.Root outPut = result;
ImageWeatherIcon.Source = string.Format("https://samana.softnames.com/icons/{0}.png", outPut.weather[0].icon);
LabelTemprature.Text = string.Format("{0}", ToCelsius(outPut.main.temp));
LabelDescription.Text = string.Format("{0}", outPut.weather[0].description);
LabelName.Text = string.Format("{0}", outPut.name);
}
}
private double ToCelsius(double kelvin)
{
double celsius;
celsius = (kelvin - 273.15);
return celsius;
}
public class LocationInfo
{
public double? latitude { get; set; }
public double? longitude { get; set; }
public string admin_area { get; set; }
public string country_code { get; set; }
public string country_name { get; set; }
public string feature_name { get; set; }
public string locality { get; set; }
public string postal_code { get; set; }
public string sub_admin_area { get; set; }
public string sub_locality { get; set; }
public string sub_thoroughfare { get; set; }
public string thoroughfare { get; set; }
}
public async Task<LocationInfo> GetLocation()
{
var UserLocation = new LocationInfo();
try
{
var last_known_location = await Geolocation.GetLastKnownLocationAsync();
if (last_known_location != null)
{
UserLocation.latitude = last_known_location.Latitude;
UserLocation.longitude = last_known_location.Longitude;
}
else
{
var request = new GeolocationRequest(GeolocationAccuracy.Default);
var location = await Geolocation.GetLocationAsync(request);
if (location != null)
{
UserLocation.latitude = location.Latitude;
UserLocation.longitude = location.Longitude;
var placemarks = await Geocoding.GetPlacemarksAsync(location.Latitude, location.Longitude);
var placemark = placemarks?.FirstOrDefault();
if (placemark != null)
{
UserLocation.admin_area = placemark.AdminArea;
UserLocation.country_code = placemark.CountryCode;
UserLocation.country_name = placemark.CountryName;
UserLocation.feature_name = placemark.FeatureName;
UserLocation.locality = placemark.Locality;
UserLocation.postal_code = placemark.PostalCode;
UserLocation.sub_admin_area = placemark.SubAdminArea;
UserLocation.sub_locality = placemark.SubLocality;
UserLocation.sub_thoroughfare = placemark.SubThoroughfare;
UserLocation.thoroughfare = placemark.Thoroughfare;
}
}
}
}
catch (Exception ex)
{
Crashes.TrackError(ex, new Dictionary<string, string>
{
{ "Page", "Settings" },
{ "Where", "GetLocation" }
});
UserLocation.latitude = null;
UserLocation.longitude = null;
}
return UserLocation;
}
private async void Button_Clicked(object sender, EventArgs e)
{
var location_data = await GetLocation();
string url = "https://samples.openweathermap.org/data/2.5/weather?lat=" + location_data.latitude + "&lon=" + location_data.longitude + "&appid=" + api_key;
using (WebClient web_client = new WebClient())
{
var json = web_client.DownloadString(url);
var result = JsonConvert.DeserializeObject<WeatherInfo.Root>(json);
WeatherInfo.Root outPut = result;
ImageWeatherIcon.Source = string.Format("https://samana.softnames.com/icons/{0}.png", outPut.weather[0].icon);
LabelTemprature.Text = string.Format("{0}", ToCelsius(outPut.main.temp));
LabelDescription.Text = string.Format("{0}", outPut.weather[0].description);
LabelName.Text = string.Format("{0}", outPut.name);
}
}
}
}
Thanks,
Jassim