Reputation: 5375
I have a Xamarin.Forms app that uses push notifications. For some reason, the following line:
(App.Current.MainPage as MainPage)?.AddMessage(body);
that is called from Android native OnMessageReceived()
, throws NullReferenceException
.
Why can this happen? Isn't App.Current
to be accessible from the platform-specific project?
Edit:
Here is the full OnMessageReceived()
code:
public override void OnMessageReceived(RemoteMessage message)
{
base.OnMessageReceived(message);
string messageBody;
if (message.GetNotification() != null)
{
messageBody = message.GetNotification().Body;
}
// NOTE: test messages sent via the Azure portal will be received here
else
{
messageBody = message.Data.Values.First();
}
// convert the incoming message to a local notification
SendLocalNotification(messageBody);
// send the incoming message directly to the MainPage
SendMessageToMainPage(messageBody);
}
Upvotes: 1
Views: 267
Reputation: 9990
App.Current.MainPage
may contain any Page, not necessary your type MainPage
, for example it could be NavigationPage
. As the result of casting is null
it is clear that it is of some other type.
Also it could happen that nothing is assigned to it.
Upvotes: 2