0

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;
    }
}
George Edwards
  • 8,017
  • 16
  • 64
  • 135
  • Well, it looks like no instance of adapter being passed to the `HomePage` constructor. Are you using some DI container? Or creating instance of `HomePage` manually and missed appropriate argument? – Andy Korneyev Feb 02 '16 at 11:10
  • 1
    Ok, but does `SetAdapter` ever being called? If not - it remains uninitialized. Habe you debugged it? – Andy Korneyev Feb 02 '16 at 11:14
  • Ahh, got it thanks @AndyKorneyev I need this line: `App.SetAdapter (Adapter.Current);` in my AppDeleagate file in the platform specific project. It is the Cross-platform structure which got me! Thank you for youe help. – George Edwards Feb 02 '16 at 11:16
  • ^ And it must be before new app is called – George Edwards Feb 19 '16 at 14:24

0 Answers0