Xamarin: Failed to create JavaTypeInfo for class … due to System.NullReference Exception

In my Xamarin\Android project, I wanted to use a WebView and add a JavascriptInterface to enable communication between my app and the JavaScript inside the WebView. I found an example here which was quite easy and straight forward. To explore things a little bit more, I wanted to add a JavaScript-callable method that accepts a parameter of type System.Object, call it with random objects from JavaScripts and see what these JavaScript objects transform to in the .NET world.

public class JavaScriptInterop : Java.Lang.Object
{
    public JavaScriptInterop(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer) { }

    public JavaScriptInterop() { }

    [Export]
    [JavascriptInterface]
    public void InitContent(object obj)
    {
        Console.WriteLine(obj.GetType().AssemblyQualifiedName);
    }
}

Bu I got a compiler error 🙁

Failed to create JavaTypeInfo for class: SpaceTime.Droid.WebView due to System.NullReferenceException: Object reference not set to an instance of an object.
at Java.Interop.Tools.JavaCallableWrappers.JavaCallableWrapperGenerator…

I guess anybody familiar with Xamarin has already seen what my mistake was, but I’m still not that familiar, so I had to learn that…

  1. The ExportAttribute is used to instruct the “Java code generator to export a Java method that becomes an Android Callable Wrapper (ACW)” and
  2. System.Object is not a Java object (duh) and the Java code generator has no idea how to handle it.

So the simple fix to my problem was to switch the parameter type from System.Object to Java.Lang.Object. Now the Java code generator can properly generate an ACW and the compilation succeeds.

[Export] 
[JavascriptInterface] 
public void InitContent(Java.Lang.Object obj) 
{ 
    Console.WriteLine(obj.GetType().AssemblyQualifiedName); 
}

This is a silly mistake on my side, granted. But a slightly more expressive error message would have been very helpful.

1qxh2q

Freelance full-stack .NET and JS developer and architect. Located near Cologne, Germany.

Leave a Reply

Your email address will not be published. Required fields are marked *