Tag Archives: NewGlobalRef

[Solved] NDK JNI DETECTED ERROR IN APPLICATION: use of deleted local reference

error reason

Most of the job objects created by jnienv are local variables, which can no longer be used after they are out of function scope

So be sure to turn these variables into global variables, pass them to external pointers or references, and release them when they are used up

correct code


	//char Arrays to jstring
	void toString(const char *charArray, jstring &string) {
	    JNIEnv *env = nullptr;
	    bool detached = JNI::jvm->GetEnv((void **) &env, JNI_VERSION_1_6) == JNI_EDETACHED;
	    if (detached) JNI::jvm->AttachCurrentThread(&env, nullptr);
	    jstring localString = env->NewStringUTF(charArray);
	    string = (jstring) env->NewGlobalRef(localString);
	    if (detached) JNI::jvm->DetachCurrentThread();
	}

	//Calling Methods
	jstring string = nullptr;
	toString(charArray, string);
	//use
	env->CallVoidMethod(interface, onErrorMethod, code, string);
	//release
	env->DeleteGlobalRef(string);
	string = nullptr;