1

I am writing an app to send a broadcast message to another app in Xamarin.Forms.My first step is to try sending a BC message to myself. Can someone maybe explain me why i get a nullpointer exception after executing the SendBC Method in MainActivity.cs? And perhaps the solution? :-)

Errormessage:

java.lang.nullpointerexception: 'attempt to invoke virtual method 'void android.content.context.sendbroadcast(android.content.intent)' on a null object reference xamarin

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="RFID_ScannerApp.MainPage">

    <StackLayout Orientation="Horizontal">
        <Label Text="Click to start broadcast"/>
        <Button Text="Start"
                Clicked="btnSendBroadcast"/>
    </StackLayout>

</ContentPage>

MainPage.xaml.cs

namespace RFID_ScannerApp
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void btnSendBroadcast(object sender, EventArgs e)
        {
            Xamarin.Forms.DependencyService.Get<IBroadcastService>().SendBC();
        }
    }
}

IBroadcastService.cs

namespace RFID_ScannerApp
{
    public interface IBroadcastService
    {
        void SendBC();
    }
}

MainActivity.cs

[Activity(Label = "RFID_ScannerApp", Icon = "@mipmap/icon", Theme = "@style/MainTheme", 
MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | 
ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | 
ConfigChanges.SmallestScreenSize )]
public class MainActivity : 
global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, IBroadcastService
{

    private static Receiver receiver;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        receiver = new Receiver();
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        LoadApplication(new App());

        
        
        
    }
    public override void OnRequestPermissionsResult(int requestCode, string[] 
        permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, 
            grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    protected override void OnResume()
    {
        base.OnResume();
        RegisterReceiver(receiver, new IntentFilter("com.xamarin.example.TEST"));
        // Code omitted for clarity
    }

    protected override void OnPause()
    {
        UnregisterReceiver(receiver);
        // Code omitted for clarity
        base.OnPause();
    }

    public void SendBC()
    {
        Intent message = new Intent("com.xamarin.example.TEST");
        // If desired, pass some values to the broadcast receiver.
        message.PutExtra("key", "value");
        SendBroadcast(message);
    }
}

Receiver.cs

[BroadcastReceiver(Enabled = true, Exported = false)]
public class Receiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        Toast.MakeText(context, "Received intent!", ToastLength.Short).Show();
    }
}
DaveR
  • 63
  • 1
  • 10
  • If I had to guess, I'd bet on `Xamarin.Forms.DependencyService.Get()` does not actually resolve the dependency. – Fildor Feb 21 '23 at 07:13
  • No the dependency service works fine. Tested it. Seems to be that the SendBroadcast() message has a problem. Attempt to invoke virtual method 'void android.content.Context.sendBroadcast(android.content.Intent)' on a null object reference – DaveR Feb 21 '23 at 08:32
  • 2
    `on a null object reference` means that you are _invoking it_ on a `null`. So you are practically doing `null.sendBroadCast(intent)`. – Fildor Feb 21 '23 at 08:37
  • If this should be the reason, then nothing should be executed which is in the SendBC method. Right? System.Console.WriteLine("Send DMC button clicked"); is executed without any problems. Only the SendBroadcast causes problems – DaveR Feb 21 '23 at 08:57
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Fildor Feb 21 '23 at 09:16
  • 1
    Where is `SendBroadcast(message);` defined? And there is no `System.Console.WriteLine("Send DMC button clicked");` in the code above (or I missed it). – Fildor Feb 21 '23 at 09:17
  • I know what a NullpointerException is :-) But this one makes no sense for me :-| I added the WriteLine to test if the dependencySystem works correct – DaveR Feb 21 '23 at 09:22

1 Answers1

1

I finally got it. I had no context to execute SendBroadcast(intent):

Context context = Android.App.Application.Context;
context.SendBroadcast(intent); 
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
DaveR
  • 63
  • 1
  • 10