Home » Android » c# – Xamarin forms DisplayAlert not showing when called from a function called by a delegate

c# – Xamarin forms DisplayAlert not showing when called from a function called by a delegate

Posted by: admin June 15, 2020 Leave a comment

Questions:

When I call Greet from inside the size function DisplayAlert displays an alert as expected However when it is called from the delegate after an event it will Log to the output with the correct name (Greet Has been Called) but the DisplayAlert does not show.

   public class CustomPage : ContentPage
   {
         ...

        protected override void OnValidSizeAllocated(double width, double height)
        {
            ...

            Greet("Test");

            app.FB.GetName();

            app.FB.NameRecieved += (s,e) =>
            {
                Greet(e.Name);  
            };

        }

        public void Greet(string name)
        {
            Utils.Log("Hey " + name);
            DisplayAlert("Hey " + name, "Welcome", "OK");
        }

    }

The Code above outputs “Hey Test” and then an alert comes up saying “Hey Test, Welcome” with an OK button then it outputs “Hey Leo” (which is correct because that is the name from the Facebook account) but then no Alert shows.

How to&Answers:

Is NameReceived fired inside GetName function?

Maybe you need to put app.FB.GetName() after the “+={…};” block.

If nameReceived is correctly fired maybe Greet is not running on ui thread,
try wrap your display code in

Device.BeginInvokeOnMainThread (() => {
 DisplayAlert("Hey " + name, "Welcome", "OK");
});

as described here

Answer:

Why don’t you create a PageBase class that implements DisplayAlert and wraps it in BeingInvokeOnMainThread so that you do not have to keep re-writing it:

public class PageBase : ContentPage
{        
    public void DisplayAlert(string message,string title, string button)
    {
         Device.BeginInvokeOnMainThread (() => {
              DisplayAlert(message, title, button);
              });
    }

}