0

im trying to implement a Barcode Scanner on my project in Xamarin Forms. When i press the back button on the scanning page my app crash. I am getting the following error: System.NullReferenceException: 'Object reference not set to an instance of an object.'

This is my code:

ScanService.cs

public interface ScanningService
{
    Task<string> ScanAsync();

}

My code behind:

var scanner = DependencyService.Get<ScanningService>();
        var result = await scanner.ScanAsync();
        if (result != null){.....}

QRscanningService (On Android):

   class QrScanningService : ScanningService
    {
       

        public async Task<string> ScanAsync()
        {

            var optionsCustom = new MobileBarcodeScanningOptions();

            var scanner = new MobileBarcodeScanner()
            {
                TopText = "Acerca la cámara",
                BottomText = "Toca la pantalla para enfocar",

            };
            var scanResult = await scanner.Scan(optionsCustom);

            return scanResult.Text;
        }

    }

Any contribution will be apreciated.

2 Answers2

0

I believe the error occurs inside QRscanningService (On Android).

It is because you're trying to use "Text" from scanResult and scanResult is null

To avoid this, change the last line to something like this:

return scanResult == null ? null: scanResult.Text;
JEFF
  • 41
  • 3
0

I solved it with the following code on my code behind:

var overlay = new ZXingDefaultOverlay
{
    ShowFlashButton = true,
    TopText = "Toca la pantalla para enfocar",
    BottomText = string.Empty
};

overlay.BindingContext = overlay;

scanPage = new ZXingScannerPage(null, overlay);
            
overlay.FlashButtonClicked += (s, ed) =>
{
    scanPage.ToggleTorch();
};

scanPage.OnScanResult += (result) =>
{
    scanPage.IsScanning = false;

    Device.BeginInvokeOnMainThread(() =>
    {
        _ = Navigation.PopModalAsync();
        try
        {
            TxtidR.Text = result.Text;
        }
        catch (Exception)
        {
            throw;
        }
    });
};

await Navigation.PushModalAsync(scanPage);
var scanner = DependencyService.Get<ScanningService>();
}

I hope it works for you!