Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

Scan a QR Code with device camera

$
0
0

Hello everyone,

I try to create a simple app that can scan a qr code and process its data.

I made it with the following tutorial: https://www.c-sharpcorner.com/article/qr-code-scanner-in-xamarin-forms2/

Unfortunately, when clicking on the Button, I get Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.

Please let me share my code:

MainPage.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"
         xmlns:local="clr-namespace:Qr_Code_Scanner"
         x:Class="Qr_Code_Scanner.MainPage">
<StackLayout Spacing="10">
    <Button Text="Click"  
            x:Name="BtnScan"  
            Clicked="BtnScan_Clicked"/>
    <Entry x:Name="txtBarcode"  
           Placeholder="Text scanned"/>
</StackLayout>

IQrScanningService.cs:

public interface IQrScanningService
{
    Task<string> ScanAsync();
}

QrScanningService.cs:

using System.Threading.Tasks;
using ZXing.Mobile;
using Xamarin.Forms;
using Qr_Code_Scanner.Services;

[assembly: Dependency(typeof(QR_Code_Scanner.Droid.Services.QrScanningService))]

namespace QR_Code_Scanner.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;
        }
    }
}

MainPage.xaml.cs:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }
    async void BtnScan_Clicked(object sender, EventArgs e)
    {
        try
        {
            var scanner = DependencyService.Get<IQrScanningService>();
            var result = await scanner.ScanAsync();
            if (result != null)
            {
                txtBarcode.Text = result;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

Anybody an idea what could be the problem?

I would be very thankful for every answer.

Best regards!


Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>