Search code examples
xamarin.formszxingbarcode-scanner

NullPointerException with zxing library for QR scanning (android app Xamarin Froms)


The zxing QR code reader gives crash with Java.Lang.NullPointerException: 'Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference' below are the code which i added.

        {
            try
            {
                Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

                base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
                PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
                global::ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            }
            catch (Exception)
            {
                return;
            }
        }
// and 
 try
            {
                ZXing.Mobile.MobileBarcodeScanner.Initialize(Application);

                ZXing.Net.Mobile.Forms.Android.Platform.Init();
            }
            catch (Exception)
            {
                return;
            }
 // on the on create 

// button click 

        private async void Button_Clicked(object sender, EventArgs e)
        {
            try
            {
                _scanPage = new ZXingScannerPage();
                if (_scanPage != null)
                {
                    _scanPage.OnScanResult += (result) =>
                    {
                        _scanPage.IsScanning = false;

                        Device.BeginInvokeOnMainThread(() =>
                        {
                            Navigation.PopAsync();
                            DisplayAlert("Scanned Barcode", result.Text, "OK");
                        });
                    };
                }

                await Navigation.PushAsync(_scanPage).ConfigureAwait(true);
            }
            catch (Exception)
            {
                return;
            }
        }

The Plugin Details are below

ZXing.Net.Mobile 2.4.1 and ZXing.Net.Mobile.Forms 2.4.1

please suggest me is there is any other plugin which we can use instead


Solution

  •  updated the Initialize scanner code in Main Activity, below are the code 
    global::Xamarin.Forms.Forms.Init(this, bundle);
                //-->Initialize scanner
                MobileBarcodeScanner.Initialize(this.Application);
    

    and it work fine now