I’m using Application.Current.MainPage.DisplayAlert
from a separate class and I’m getting this error:
System.NullReferenceException: ‘Object reference not set to an instance of an object.’
App.xaml.cs
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
}
MainPage.cs
public partial class MainPage : ContentPage
{
private static readonly DisplayMessage DisplayMessage = new();
public MainPage()
{
InitializeComponent();
DisplayMessage.Display();
}
}
DisplayMessage.cs
public class DisplayMessage
{
public async void Display()
{
await Application.Current.MainPage.DisplayAlert("Hello World", "Welcome", "OK");
}
}
I found this article proposing this solution but it doesn’t help
public static Page RootPage;
public App()
{
InitializeComponent();
MainPage = new MainPage();
App.RootPage = this.MainPage;
}
App.RootPage.DisplayAlert(title, message, ok);
Does someone have a direction to find out ? Thanks a lot.
>Solution :
The problem is that you’re trying to access the MainPage
instance before it has finished construction.
Instead of doing this:
public partial class MainPage : ContentPage
{
private static readonly DisplayMessage DisplayMessage = new();
public MainPage()
{
InitializeComponent();
DisplayMessage.Display();
}
}
You can do the following, which should work:
public partial class MainPage : ContentPage
{
private static readonly DisplayMessage DisplayMessage = new();
public MainPage()
{
InitializeComponent();
}
public void ShowMessage()
{
DisplayMessage.Display();
}
}
Then, after construction finished, the ShowMessage()
method can be called, which in turn will display the message.
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
MainPage.ShowMessage();
}
}
Now, the overall design of your code is debatable, but making these changes should lead to a usable solution.
Update:
You may also want to add a null-check to the following piece of code:
public class DisplayMessage
{
public async void Display()
{
//note the "?"
await Application.Current.MainPage?.DisplayAlert("Hello World", "Welcome", "OK");
}
}
Note the ?
which serves to ensure that DisplayAlert()
only gets called when MainPage
is set to an instance.