Calling Java Methods from Native C in Android
When integrating Java and C code in Android, it may become necessary to call Java methods from native C code. This article addresses a specific issue faced when attempting to invoke a Java method named "messageMe" from native code within the "getJniString" method.
In the provided code snippet, the developer attempts to call "messageMe" from native C within the "getJniString" method. However, the compilation fails with a "NoSuchMethodError" exception, indicating that the method name is incorrect.
The issue lies in the way the "messageMe" method is invoked in the native code:
<code class="cpp">jobject result = env->CallObjectMethod(jstr, messageMe);</code>
Here, the "jstr" variable represents the Java object on which the method should be called, and "messageMe" refers to the method ID. However, since "messageMe" is a method of the "MainActivity" class (as defined in the Java code), it cannot be directly passed to "CallObjectMethod" because it would be equivalent to calling "jstr.myMethod()", which is incorrect.
To resolve this issue, the native code should pass the "obj" variable, which represents the instance of the "MainActivity" class, to "CallObjectMethod" as follows:
<code class="cpp">jobject result = env->CallObjectMethod(obj, messageMe);</code>
Furthermore, if the "messageMe" method is defined as void (as it is in the given code), "CallVoidMethod" should be used instead of "CallObjectMethod":
<code class="cpp">env->CallVoidMethod(obj, messageMe, jstr);</code>
If a result is expected from the "messageMe" method, the Java code and JNI signature will need to be modified to return a value.
The above is the detailed content of Why am I getting a \'NoSuchMethodError\' when calling a Java method from native C in Android?. For more information, please follow other related articles on the PHP Chinese website!