NullReferenceException When Using IAdapter in BLELoginServiceAndroid Class

Fede Lovera 0 Reputation points
2024-10-23T17:14:28.3866667+00:00

I am using the Plugin.BLE in a .NET MAUI project to manage BLE connections. A NullReferenceException occurs when attempting to access the adapter inside new methods of my BLELoginServiceAndroid class, despite the adapter working fine in older methods. Various approaches to initialize the adapter have been tried, but the issue persists.

Using Plugin BLE version 3.0.0 with .NET 8 MAUI and Blazor WASM.

Here is my current class implementation:

internal class BLELoginServiceAndroid : IBLELoginService 
{ 
    private IAdapter adapter = CrossBluetoothLE.Current.Adapter;
    private bool adapterInitialized = false; 
    private IMemoryLog log;

    public async void Initialize()
    {
        var state = ble.State;
        ble.StateChanged += (s, e) => 
        {
            Console.WriteLine($"The bluetooth state changed to {e.NewState}");
        };

        adapter.ScanTimeout = 1300; 

        adapter.DeviceDiscovered += (s, a) => 
        {
            log.AddLog($"DeviceDiscovered");
            byte[] manufacturer = Array.Empty<byte>();
        };

        adapter.DeviceConnected += async (s, d) => await LoginWithCredentials(d.Device);
    }

    public async Task DoLogin(int appId, int[] accesosIds, byte[] cryptedPinPwd)
    {
        this.appId = appId;
        this.cryptedPinPwd = cryptedPinPwd;
        this.idAccesos = accesosIds;
        await adapter.StartScanningForDevicesAsync();
        await Connect(null, null);
    }

    public async Task<Dictionary<string, object>> ScanAndGetBeaconInfo(int appId, int[] accesosIds, byte[] cryptedPinPwd)
    {
        this.appId = appId;
        this.cryptedPinPwd = cryptedPinPwd;
        this.idAccesos = accesosIds;
        var beaconInfo = new Dictionary<string, object>();
        await adapter.StartScanningForDevicesAsync();
        //NullReferenceException here
        await Task.Delay(1000);
    }
}

Possible Cause: The issue might be related to the asynchronous initialization of the adapter, as it seems not fully initialized when accessed in the ScanAndGetBeaconInfo method, despite functioning correctly in other methods.

Question: What is the recommended way to handle the initialization of CrossBluetoothLE.Current.Adapter in asynchronous contexts or during device scanning to avoid these types of errors? Suggestions on improving the initialization or lifecycle management of the adapter would be very helpful.

Developer technologies | .NET | .NET MAUI
{count} votes

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.