Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin forms inside Constructor display alert not showing?

I want to display alert in my main page loading time. So i declared display alert in my constructor. But i didn't get any response.

I have attached my sample code.

public Home()
{
    InitializeComponent();
    if (!(Plugin.Connectivity.CrossConnectivity.Current.IsConnected))
    {

        if (System.IO.File.Exists(path + "App" + "/Data.txt"))
        {
            Device.BeginInvokeOnMainThread(async () =>
            {
                await DisplayAlert("Success", "Saved", "OK");
            });

        }
        else
        {
            Device.BeginInvokeOnMainThread(async () =>
            {
                await DisplayAlert("Oops", "Login Required", "OK");
            });

        }

    }
    else
    {
        GetDetails();
    }

}
like image 448
Balu Avatar asked Dec 19 '22 00:12

Balu


2 Answers

The constructor is meant to keep Initialization code. TheOnAppearing() method is called when the Page is about to be displayed.The displayAlert() will succeed inside this method. This is the sample code.

protected override void OnAppearing()
    {

        Application.Current.MainPage.DisplayAlert("Success", "Saved", "OK");

        base.OnAppearing();

}

Keep you initialization code in the constructor or new Task(Init).Start(); as suggested in other answer. Save the status of if else in field of type bool. Alter the message in the OnAppearing() method according to the field.

like image 164
Paramjit Avatar answered Dec 20 '22 13:12

Paramjit


You can not directly await a Task within the .ctor of a class (search SO there are plenty of Q&A on this).

In your .ctor, after the InitializeComponent start a void Task (fire and forget style):

new Task(Init).Start();

The void task Init will look like:

async void Init()
{
    if (!(Plugin.Connectivity.CrossConnectivity.Current.IsConnected))
    {
        ~~~
    }
    else
    {
        GetDetails();
    }
}
like image 23
SushiHangover Avatar answered Dec 20 '22 13:12

SushiHangover