Xamarin 表单:使用 ZXing.Net.Mobile 进行扫描时 System.NullReferenceException?

Xamarin forms: System.NullReferenceException when using ZXing.Net.Mobile for scanning?

我正在使用 ZXing.Net.Mobile NuGet 包来扫描条码编号。我已经按照 blog.

做了所有事情

我的代码

//Main Project Interface
public interface IQrScanningService  
{  
   Task<string> ScanAsync();  
}

//Android part implementation
[assembly: Dependency(typeof(XFBarcode.Droid.Services.QrScanningService))]  
namespace projectname.Droid.Services  
{  
    public class QrScanningService : IQrScanningService  
    {  
        public async Task<string> ScanAsync()  
        {  
            var optionsDefault = new MobileBarcodeScanningOptions();  
            var optionsCustom = new MobileBarcodeScanningOptions();  
  
            var scanner = new MobileBarcodeScanner()  
            {  
                TopText = "Scan the QR Code",  
                BottomText = "Please Wait",  
            };  
  
            var scanResult = await scanner.Scan(optionsCustom);  
            return scanResult.Text;  
        }  
    }  
}  

但是当我执行时,我得到 System.NullReferenceException: 'Object reference not set to an instance of an object.'。我还缺少什么?我看到了一个类似的帖子 here 但不知道如何使用 GitHub.

中的包下载

您错过了初始化步骤。

试试这个:

public async Task<string> ScanAsync()
    {
        //Initialize the scanner first so it can track the current context
        MobileBarcodeScanner.Initialize(MainActivity.Instance.Application);

        var optionsDefault = new MobileBarcodeScanningOptions();
        var optionsCustom = new MobileBarcodeScanningOptions();

        var scanner = new MobileBarcodeScanner()
        {
            TopText = "Scan the QR Code",
            BottomText = "Please Wait",
        };

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

在您的 MainActivity 中:

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    public static MainActivity Instance;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);
        Instance = this;
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        LoadApplication(new App());
    }

}

您也可以直接在 MainActivity OnCreate() 方法中初始化。

protected override void OnCreate(Bundle savedInstanceState)
{
    TabLayoutResource = Resource.Layout.Tabbar;
    ToolbarResource = Resource.Layout.Toolbar;

    base.OnCreate(savedInstanceState);
    Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    MobileBarcodeScanner.Initialize(Application); //initialize  here
    global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
    LoadApplication(new App());
}