Posts Tagged ‘Scanning’

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.