Issue
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.
Solution
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!
Answered By - Jair Olivares
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.