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();
}
}