Zxing.net.mobile: System.NullReferenceException

Created on 7 Dec 2017  路  31Comments  路  Source: Redth/ZXing.Net.Mobile

I'm using the latest version available on Nutget from ZXing.Net.Mobile. For the development of a mobile app on android I use Xamarin with Visual Studio 2017. I received this error:

Xamarin caused by: android.runtime.JavaProxyThrowable: System.NullReferenceException: Object reference not set to an instance of an object
at ZXing.Mobile.CameraAccess.CameraController.ApplyCameraSettings () [0x00007] in <60d925e3f0f44738b90c37526d1dc7c4>:0
at ZXing.Mobile.CameraAccess.CameraController.RefreshCamera () [0x00010] in <60d925e3f0f44738b90c37526d1dc7c4>:0
at ZXing.Mobile.CameraAccess.CameraAnalyzer.RefreshCamera () [0x00001] in <60d925e3f0f44738b90c37526d1dc7c4>:0
at ZXing.Mobile.ZXingSurfaceView+d__4.MoveNext () [0x00083] in <60d925e3f0f44738b90c37526d1dc7c4>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <8ed327f420564af2812805578d7ed8e0>:0
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_0 (System.Object state) [0x00000] in <8ed327f420564af2812805578d7ed8e0>:0
at Android.App.SyncContext+<>c__DisplayClass2_0.b__0 () [0x00000] in <68f5700d71b949eaa6ee7c03adb761a6>:0
at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in <68f5700d71b949eaa6ee7c03adb761a6>:0
at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00008] in <68f5700d71b949eaa6ee7c03adb761a6>:0
at (wrapper dynamic-method) System.Object:f7879d27-1273-4c61-bab3-3b0002f833ab (intptr,intptr)
at mono.java.lang.RunnableImplementor.n_run(Native Method)
at mono.java.lang.RunnableImplementor.run(RunnableImplementor.java:30)
at android.os.Handler.handleCallback(Handler.java:819)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:210)
at android.app.ActivityThread.main(ActivityThread.java:5988)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:742)

The error was reported on a Samsung Galaxy J7 and a Huawei Y5 2017
The code I use is the following:
聽 var scanner = new ZXing.Mobile.MobileBarcodeScanner
聽聽聽聽聽聽聽聽聽聽聽聽 {
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 UseCustomOverlay = false,
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 TopText = topText,
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 BottomText = bottomText
聽聽聽聽聽聽聽聽聽聽聽聽 };
聽聽聽聽聽聽聽聽聽聽聽聽 var result = await scanner.Scan ();
聽聽聽聽聽聽聽聽聽聽聽聽 if (result! = null)
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 return result.Text;
聽聽聽聽聽聽聽聽聽聽聽聽 return string.Empty;

Please, could you help me with this error? Thank you

Most helpful comment

You need Zxing.Net.Moblie in addition to Zxing.Net.Mobile.Forms in a Xamarin.Forms project for Android it seems. Can that not go in the dependencies make it all easier?

All 31 comments

I experience the same error in version 2.2.9. It appeared out of the blue... Thought that an updated to the latest will fix this issue but it seams rather new.

I've just been hit by the same problem in v2.2.9. Any updates on this?

Make sure you're adding:

ZXing.Net.Mobile.Forms.Android.Platform.Init();

and:

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
    global::ZXing.Net.Mobile.Forms.Android.PermissionsHandler.OnRequestPermissionsResult (requestCode, permissions, grantResults);           
}

To your main Activity...

Both of your suggestions are present in my main Activity. I am using the ZXing.Net.Mobile library not the ZXing.Net.Mobile.Forms could there be a difference between the two libs?

@ChristophvanderFecht you also need to initialize the library at some point for Android before you use it by calling:

ZXing.Mobile.MobileBarcodeScanner.Initialize(this.Application);

And of course wire up your permission handler appropriately still:

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
    global::ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

I麓m not using Xamarin Forms. I麓m using Xamarin with MvvmCross. In three views that I need scan, I used:
MobileBarcodeScanner.Initialize(Application);
on OnCreate method. My BaseView handles permissions method, I added now the line for Zxing麓s permissions handler, but previously he worked well, only occasionally I got this error. I hope that with that it is solved, I will wait a few days to see if there is no more report of that error. Thank you very much

@Redth I think I am initializing correctly...

Here are the parts of my Main Activite which you referenced.

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        --- Snipped---

        // init zxing scanner
        ZXing.Mobile.MobileBarcodeScanner.Initialize(this.Application);

        ---Snipped---
    }

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
    {
        try
        {
            ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
        catch (Exception ex)
        {

            throw;
        }
    }

And here is the code that actually uses the lib

    private async Task ScanQrCodeAsync()
    {
        var scanner = new MobileBarcodeScanner();
        ZXing.Result result = null;

        try
        {
            var options = new MobileBarcodeScanningOptions()
            {
                AutoRotate = false
            };

            result = await scanner.Scan(options);
        }
        catch (Exception ex)
        {
            scanner.Cancel();
            throw;
        }

        if (result != null)
        {
            // navigate away...
        }
        else
        {
            scanner.Cancel();
        }
    }

Did I miss anything or do you see any errors here?
Thx!

I'm initialising the library in the same way you suggest and it works most of the time, but there are just some devices where this crash occurs.

Ok it seems like for others the same thing is happening. It crashes on _some_ devices.

Can everyone share any devices and their OS version this is known to crash on?

in testing with a Kyocera E6810 DuraForce running Android 7.1.2, it appears that in CameraController.cs 218

    private void ApplyCameraSettings()
    {
        var parameters = Camera.GetParameters();
        parameters.PreviewFormat = ImageFormatType.Nv21;

Camera is NULL after the scan executes, causing the exception.

If I catch the Exception and just return from ApplyCameraSettings, things continue to work normally.

There may be side-effects to that approach that I don't see, however.

Here is a list with devices that have crashed due to this issue:

Galaxy Core - 4.1.2
Mi 4c - 5.1.1
Redmi Note 3 - 5.0.2
HM Note 2 - 5.0.2
ALCATEL ONETOUCH POP 3 (5) - 5.1
Coolpad R108 - 5.1.1
HM 2LTE-CU - 4.4.4
Galaxy Note4 - 6.0.1

I have tested it on
(UMI-London - 6.0)

It crashed on the HTC Bolt and the Genymotion Google Pixel C simulator. I applied the source code changes made by kkabala for issue #656 and then everything worked

Same issue. If i start the scan, see Camera for a secound and than App crashed.
The Scan-Start is in a "try" so i think, isn't the Code, i use, this Crash is from ZXing.

for testing, code-snipe:

ZXing.Mobile.MobileBarcodeScanner.Initialize(this.Application);
ZXing.Mobile.MobileBarcodeScanner scanner = new ZXing.Mobile.MobileBarcodeScanner();
ZXing.Result result = null;

try
{

                var needsPermissionRequest = ZXing.Net.Mobile.Android.PermissionsHandler.NeedsPermissionRequest(this);

                if (needsPermissionRequest)
                {
                    var s = await ZXing.Net.Mobile.Android.PermissionsHandler.RequestPermissionsAsync(this);
                }


                var options = new MobileBarcodeScanningOptions()
                {
                    AutoRotate = false

                };

result = await scanner.Scan(options);

            }
            catch
            {
                scanner.Cancel();
                Toast.MakeText(this, "No communication with Camara", ToastLength.Long).Show();
            }

It crashes on

  • Lenovo P2a42 (Android 7.0)
  • Lenovo P780 (Android 4.4.2)

I have next code:

protected override void OnCreate( Bundle bundle )
{
    TabLayoutResource = Resource.Layout.Tabbar;
    ToolbarResource = Resource.Layout.Toolbar;

    base.OnCreate( bundle );

    global::Xamarin.Forms.Forms.Init( this, bundle );
    global::ZXing.Net.Mobile.Forms.Android.Platform.Init();

    LoadApplication( new App() );
}

public override void OnRequestPermissionsResult( int requestCode, string[] permissions, Permission[] grantResults )
{
    global::ZXing.Net.Mobile.Forms.Android.PermissionsHandler.OnRequestPermissionsResult( requestCode, permissions, grantResults );
    base.OnRequestPermissionsResult( requestCode, permissions, grantResults );
}

The line LoadApplication( new App() ); throws the null reference exception.

I'm getting the same error. It crashed on

  • Samsung Galaxy S4 mini (Android 4.4.2)

This is the code I'm using:

protected override void OnCreate( Bundle bundle )
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;

base.OnCreate( bundle );

global::Xamarin.Forms.Forms.Init( this, bundle );
global::ZXing.Net.Mobile.Forms.Android.Platform.Init();

LoadApplication( new App() );

}

public override void OnRequestPermissionsResult( int requestCode, string[] permissions, Permission[] grantResults )
{
global::ZXing.Net.Mobile.Forms.Android.PermissionsHandler.OnRequestPermissionsResult( requestCode, permissions, grantResults );
base.OnRequestPermissionsResult( requestCode, permissions, grantResults );
}

Hey, any update on this?

@Redth from App Center, those are the devices throwing this exception

appcenter

Lately the error is reoccurring within my apps. I found out that it seams that this error only occurs when the app is run in DEBUG mode. I asked our QS team (who are only testing RELEASE versions) if they had encountered that error from time to time and they said no.
Maybe this helps a bit finding the source of the error.

I do believe 54c6ef72a8b33fc3226f7838bd0c298c5518181f will fix this issue.

I just installed 2.4.0-beta1 and am getting what I believe is the same/if not similar exception (below is stack trace).
running debug on emulated nexus 6p - android 7.1 stock
Also happens on Real Nexus 6p - android 8.1

at Xamarin.Forms.Platform.Android.FormsAppCompatActivity.InternalSetPage (Xamarin.Forms.Page page) [0x0005e] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\FormsAppCompatActivity.cs:315 
  at Xamarin.Forms.Platform.Android.FormsAppCompatActivity.SetMainPage () [0x00000] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\FormsAppCompatActivity.cs:343 
  at Xamarin.Forms.Platform.Android.FormsAppCompatActivity.LoadApplication (Xamarin.Forms.Application application) [0x0025c] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\FormsAppCompatActivity.cs:139 
  at WebAllianceMobileApp.Droid.MainActivity.OnCreate (Android.OS.Bundle bundle) [0x00068] in C:\GitRepos\WebAlliance Mobile App\WebAllianceMobileApp\WebAllianceMobileApp\WebAllianceMobileApp.Android\MainActivity.cs:32

MainActivity.cs

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            // This may cause issues
            // https://developer.xamarin.com/guides/xamarin-forms/under-the-hood/fast-renderers/
            Forms.SetFlags("FastRenderers_Experimental");

            Forms.Init(this, bundle);
            Rg.Plugins.Popup.Popup.Init(this, bundle);
            CarouselViewRenderer.Init();
            CachedImageRenderer.Init(true);
            ZXing.Net.Mobile.Forms.Android.Platform.Init();
            ZXing.Mobile.MobileBarcodeScanner.Initialize(Application);
            try
            {
                LoadApplication(new App());
            }
            catch (System.Exception ex)
            {
                var thing = ex.Message;
            }
        }

        public override void OnBackPressed()
        {
            if (Rg.Plugins.Popup.Popup.SendBackPressed(base.OnBackPressed))
            {
                // Do something if there are some pages in the `PopupStack`
            }
            else
            {
                // Do something if there are not any pages in the `PopupStack`
            }
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
        {
            global::ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

Ignore mine! Just being dumb and hadn't implemented my scanning page all the way. The location of the exception was a red herring - for some reason it was throwing the exception for the page on app startup, not when on the page when it was opened.

馃憤

Hopefully someone else can test 2.4.0-beta1 on some of these trouble devices and confirm it fixes.

I wanted to test the beta but it is not compatible with Android V6 (API 23). Will this be changed in the release?

Sorry, but I don't plan on that. Honestly you should be compiling against a newer API level anyway (you can still set your minimum support api level at runtime to something lower).

Google's going to start requiring this soon as well.

@Redth
Upgrade to 2.4.0-beta1 and clean the Android project works for me.

I am running into this issue as well.

I tried upgrading to 2.4.0-beta1 and it fails to build with VS 2017 15.6.4:

Severity    Code    Description Project File    Line    Suppression State
Error   CS0234  The type or namespace name 'Android' does not exist in the namespace 'ZXing.Net.Mobile' (are you missing an assembly reference?)    ...\MainActivity.cs 47  Active

This is the code that fails to build:
```C#
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

After changing it to use the obsolete `ZXing.Net.Mobile.Forms.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);`, I now get:

Severity Code Description Project File Line Suppression State
Error Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'zxing.portable, Version=0.16.2.0, Culture=neutral, PublicKeyToken=830ae994e36ac27d'. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'zxing.portable.dll'
at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
at Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences(DirectoryAssemblyResolver resolver, ICollection`1 assemblies, AssemblyDefinition assembly, Boolean topLevel)
at Xamarin.Android.Tasks.ResolveAssemblies.Execute(DirectoryAssemblyResolver resolver)
```

I'm using Xamarin.Forms and Android v7.1.

I was able to work around the above build error by also adding a package reference to ZXing.Net.Mobile.

    <PackageReference Include="ZXing.Net.Mobile" Version="2.4.0-beta1" />
    <PackageReference Include="ZXing.Net.Mobile.Forms" Version="2.4.0-beta1" />

However, now the scanner fails to load. The last thing I see in the debug Output for ZXing is:

03-30 17:42:09.666 D/ZXing.Net.Mobile(30724): Checking Number of cameras...
03-30 17:42:09.676 D/ZXing.Net.Mobile(30724): Found 2 cameras...
03-30 17:42:09.686 D/ZXing.Net.Mobile(30724): Found Back Camera, opening...

I'm using a Samsung Galaxy Tab A (2016) Android version 5.1.1.

Using version 2.3.2, I am able to use the scanner.

Update: version 2.4.0-beta1 loads on a Kindle Fire.

You need Zxing.Net.Moblie in addition to Zxing.Net.Mobile.Forms in a Xamarin.Forms project for Android it seems. Can that not go in the dependencies make it all easier?

I am still getting this i think its when its trying to dimiss the dialog oonly started hapening to me. This is a great libary its a shame its so old

Thanks for reporting this issue! Unforunately it took me way too long to respond 馃槶. Sorry, I apologize! Recently the source code for this project was completely refactored to modernize it. Many PR's were included in this effort, and many bugs were hopefully fixed. Please try out the latest 3.x series of NuGet packages (currently in prerelease). To try and make the project more maintainable in my spare time going forward, I've decided to close all existing issues to start with a clean slate. If you're still experiencing this issue on the newest version, please open a new issue with as much detail as possible. Thank you for your patience and understanding! Happy scanning!

Was this page helpful?
0 / 5 - 0 ratings