I am working on a C# cross-platform mobile app, based on the Xamarin Framework. The following code uses the Monkey.Robotics
plugin, which defines the IAdapter
type. This code compiles, but when run I get the following NullReference error message, even though adapter
is defined at the top of the program. What am I missing?
public partial class HomePage : ContentPage
{
// Class Definitions
ObservableCollection<IDevice> devices;
IAdapter adapter;
public HomePage(IAdapter adapter)
{
InitializeComponent();
this.adapter = adapter;
this.devices = new ObservableCollection<IDevice>();
Debug.WriteLine ("Before Button Clicked");
NewDeviceButton.Clicked += async (sender, e) => {
adapter.StartScanningForDevices (0x133D.UuidFromPartial ()); //Scan for a specific device
await Task.Delay (2000); // wait 2 seconds for the scan to complete
adapter.StopScanningForDevices ();
};
adapter.DeviceDiscovered += (object sender, DeviceDiscoveredEventArgs e) => {
Xamarin.Forms.Device.BeginInvokeOnMainThread(() => {
devices.Add (e.Device);
});
};
}
}
System.NullReferenceException: Object reference not set to an instance of an object at My_App.HomePage..ctor (IAdapter adapter) [0x00081] in /Projects/my_App/My_App/Views/HomePage.xaml.cs:72
NB: line 72 is the adapter.DeviceDiscovered
line.
This is app.cs
where my HomePage
is called from:
public class App : Application
{
static IAdapter Adapter;
public App ()
{
MainPage = new HomePage (Adapter);
}
public static void SetAdapter (IAdapter adapter) {
Adapter = adapter;
}
}