Email-sending DependencyService NullReferenceException on Android

Hello,

I'm trying to create a bug reporting form for my app which, after filling, sends an email to my address with the details.

When running on Android, I've encounter a NullReferenceException whenever I click "send" and call the DependencyService.
I'm using this plugin to get details about the device and OS.

This is the code for the "send" button response:
string MsgTitle = "NDLPCalc Bug Report " + CrossDeviceInfo.Current.Model + " " + CrossDeviceInfo.Current.Platform + " " + CrossDeviceInfo.Current.Version;
Debug.WriteLine(MsgTitle+" | "+MsgBody.Text);
DependencyService.Get<IMailService>().SendMail(MsgTitle, MsgBody.Text); //<-- Problematic Line

The string prints out with all the correct data.

For reference, this is the method I'm calling on Android:
public void SendMail(string mailTitle, string mailText)
{
Intent email = new Intent(Intent.ActionSend);
email.PutExtra(Intent.ExtraEmail, new string[] { "[email protected]" });
email.PutExtra(Intent.ExtraSubject, mailTitle);
email.PutExtra(Intent.ExtraText, mailText);
email.SetType("message/rfc822");
MainActivity.mainActivityContext.StartActivity(Intent.CreateChooser(email, "Send Email Via"));
}

And this is MsgBody:
<Editor x:Name="MsgBody"
HeightRequest="400"
VerticalOptions="StartAndExpand"/>

All the Stack Trace has to say is:
System.NullReferenceException: Object reference not set to an instance of an object.
pointing to DependencyService.Get<IMailService>().SendMail(MsgTitle, MsgBody.Text)

I can't figure out what's wrong, so any help is welcome.

Thanks in advance!

Best Answer

  • PolartsPolarts US ✭✭
    Accepted Answer
    The service should receive a title for the email (MsgTitle) and the email body text (MsgBody.Text since MsgBody is an Editor).
    The problem was that it didn't tell me which of them was null and the print showed none of them was.
    It appeared I didn't register the Dependency service properly, so my bad. Sorry for making a long post about it.

Answers

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    Which item is null? The server returned.. MsgTitle, MsgBody or MsgBody.Text

  • PolartsPolarts USMember ✭✭
    Accepted Answer
    The service should receive a title for the email (MsgTitle) and the email body text (MsgBody.Text since MsgBody is an Editor).
    The problem was that it didn't tell me which of them was null and the print showed none of them was.
    It appeared I didn't register the Dependency service properly, so my bad. Sorry for making a long post about it.
  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    Cool. You found it. That's what matters. Good job.

Sign In or Register to comment.