Getting a null reference error when working with Xamarin.Forms and ZXing for QRCode and BarCode scanning?

Posted: April 28, 2018 in Android, Development, Xamarin
Tags: , , , , , ,

I ran into this issue today when debugging on Android, so posting what took an hour to figure out ūüôā This is for when you’re getting a null reference exception when attempting to scan. I was following the instructions here, and then, well, it wouldn’t work ūüôā

Rather than using the Dependency Resolver, you’ll need to pass in the Application Context from Android. So, in the App, create a static reference to the IQrCodeScanner,, as follows:

	public partial class App : Application
	{
 
	    public static IQrCodeScanningService QrCodeScanningService;

Then, populate that static instance from the Android app, as follows:

App.QrCodeScanningService = new QrCodeScanningService(this);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());

Obviously you’ll also need a matching constructor, like so:

public class QrCodeScanningService : IQrCodeScanningService
{
    private readonly Context _context;
 
    public QrCodeScanningService(Context context)
    {
        _context = context;
    }

This solved the problem like magic for me. I hope it helps you, too!

P.S. Make sure you have the CAMERA permission. I’ve also read you may also need the FLASHLIGHT permission, although I’m not entirely sure that’s required.

Comments
  1. HECHT Franck says:

    Hi, this does not work:

    public static IQrCodeScanningService QrCodeScanningService;

    Result:
    Inconsistent accessibility: The IQrCodeScanningService field type is less accessible than App.QrCodeScanningService

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s