Fatal Exception at UnityEngine.AndroidJNI:NewGlobalRef

Hi folks,
I’m using the AppsFlyer Unity Plugin to send some events, but every time that I’m going to send a purchase event, I’m getting this error:

The code from the AppsFlyer Plugin below:

        private static AndroidJavaObject convertDictionaryToJavaMap(Dictionary<string, string> dictionary)
        {
            AndroidJavaObject map = new AndroidJavaObject("java.util.HashMap");
            IntPtr putMethod = AndroidJNIHelper.GetMethodID(map.GetRawClass(), "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
            jvalue[] val;
            if (dictionary != null)
            {
                foreach (var entry in dictionary)
                {
                    val = AndroidJNIHelper.CreateJNIArgArray(new object[] { entry.Key, entry.Value });
                    AndroidJNI.CallObjectMethod(map.GetRawObject(), putMethod,val);
                    AndroidJNI.DeleteLocalRef(val[0].l);
                    AndroidJNI.DeleteLocalRef(val[1].l);
                }
            }
           
            return map;
        }

Thanks in advance,
Vitaliano

I found what was causing the crash, you cannot create a AndroidJavaObject outside the Unity MainThread.

You can, but you have to Attach that thread to java first (and detach once you’re done).

1 Like