当我尝试激活相机(等待scanner.Scan())时出现异常:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
这是我的按钮:
private async void DodajQr(object senderr, EventArgs e)
{
var scanner = new MobileBarcodeScanner();
scanner.TopText = "Hold the camera up to the barcode\nAbout 6 inches away";
scanner.BottomText = "Wait for the barcode to automatically scan!";
//This will start scanning
ZXing.Result result = await scanner.Scan();
compId.Text = result.Text;
}
和主要活动:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
ZXing.Net.Mobile.Forms.Android.Platform.Init();
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
ZXing.Net.Mobile.Forms.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
我使用 Visual Studio 和 AndroidEmulator API34 有什么想法如何修复此代码吗?
您从 result 对象(包含扫描文本的对象)收到空引用异常。 您需要进行空引用检查。
像这样:
ZXing.Result result = await scanner.Scan();
if(result != null) {
compId.Text = result.Text;
}