我正在嘗試創建一個簡單的二維碼掃描儀應用程式,它有一個像這樣的單一視圖:

但是,當我試圖按下“CLICK”按鈕讓掃描儀吃午飯時,我得到了這個例外:
System.NullReferenceException:“物件參考未設定為物件的實體。”
這是 main.xaml 頁面:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="scanner.MainPage">
<StackLayout Spacing="10">
<Button Text="Click"
x:Name="btnScan"
Clicked="btnScan_Clicked"/>
<Entry x:Name="txtBarcode"
Placeholder="Text Do scan"/>
</StackLayout>
</ContentPage>
main.xaml.cs:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void btnScan_Clicked(object sender, EventArgs e)
{
try
{
var scanner = DependencyService.Get<Interface1>();
var result = await scanner.ScanAsync();
if (result != null)
{
txtBarcode.Text = result;
}
}
catch (Exception ex)
{ throw;
}
服務:
internal class QrScanningService : Interface1
{
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;
}
}
uj5u.com熱心網友回復:
我做了一個簡單的并遇到同樣的問題。于是在網上搜了一下,發現使用ZXing.Net.Mobile包的時候需要初始化插件。
因此,您可以將初始化的代碼添加到 MainActivity 的 OnCreate 方法中。如:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
MobileBarcodeScanner.Initialize(Application);// this line initialize the plugin
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
您可以查看有關它的檔案:https ://github.com/Redth/ZXing.Net.Mobile#android
在 ios 上檢查此鏈接:https ://github.com/Redth/ZXing.Net.Mobile#ios
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/480355.html
