Reputation: 41
I am developing an app in Xamarin.Forms using MVVM model and I use this method DisplayAlert in PageService class to Display Alerts throughout ViewModels:
public async Task DisplayAlert(string title, string message, string ok = "ok")
{
await Application.Current.MainPage.DisplayAlert(title, message, ok);
}
Everything worked just fine since I reinstalled the application on a testing device and made some minor changes that shouldn't affect MainPage. Now, whenever I call this DisplayAlert method, an exception is thrown:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Xamarin.Forms.Application.MainPage.get returned null
I really don't know where does the error come from. I googled around and the only thing I found was that there might be some problem in MainPage constructor, but in my case I don't see there any.
So now I am stuck and don't know how to move forward with this problem. Could you please at least point me in some direction on how to find out why MainPage returns null?
Big thanks to anyone responding, I hugely appreciate your suggestions.
Regards, Honza
Cheers, thank you, everyone! I finally managed to solve this issue: So I have this constructor of App which I edited as Lucas Zhang suggested and also added two breakpoints there:
public static Page RootPage { get; set; }
public App()
{
InitializeComponent();
MainPage = new MainPage(); //Breakpoint 1
App.RootPage = MainPage; //Breakpoint 2
}
I found out, that this code is being executed as following: Debbuger stops at breakpoint 1, then exception is thrown just before the debugger reaches breakpoint 2. Now, MainPage is actually Tabbed Page that consists of 4 other tabs, and all of these tabs are initialized when "MainPage = new MainPage();" is called. In one of these tabs I use a service. What this service does is basically: Initializes itself and determines whether a user has done something and if not, it displays an Alert that prompts him to do so. And all of that happens just before MainPage finishes its initialization, so of course when calling App.Current.MainPage null is returned.
So, that's it, thank you all once again!
Upvotes: 1
Views: 1296
Reputation: 18861
Make sure that you had set the MainPage in constructor of App.
public App()
{
InitializeComponent();
MainPage = new xxxPage();
}
If it still doesn't work , you could firstly use the following workaround .
public static Page RootPage;
public App()
{
InitializeComponent();
MainPage = new MainPage();
App.RootPage = this.MainPage;
}
And reference it
App.RootPage.DisplayAlert(title, message, ok);
Upvotes: 1