Calling Java Methods from C in Android: A Detailed Walkthrough
Calling Java methods from C is a common task in Android development. This article aims to provide a comprehensive solution to this problem by delving into the Java and C code and addressing a common error that may arise during this process.
Java Code Setup
The provided Java code defines a class named MainActivity with a method getJniString() that returns a string from C . The messageMe() method, which we intend to call from C , simply prints the received text.
<code class="java">public class MainActivity extends Activity { ... public void messageMe(String text) { System.out.println(text); } ... }</code>
C Code
The C code in native.cpp attempts to find the MainActivity class, retrieve the messageMe() method, and invoke it on the jstr string object. However, the error message "java.lang.NoSuchMethodError: messageMe" indicates that the messageMe() method is not found.
<code class="cpp">jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj, jint depth ){ jstring jstr = env->NewStringUTF("This string comes from JNI"); jclass clazz = env->FindClass("the/package/MainActivity"); jmethodID messageMe = env->GetMethodID(clazz, "messageMe", "(Ljava/lang/String;)V"); env->CallObjectMethod(jstr, messageMe); ... }</code>
The Fix
The error is caused by two issues:
<code class="cpp">jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj, jint depth ){ jstring jstr = env->NewStringUTF("This string comes from JNI"); ... jstring result = env->CallObjectMethod(obj, messageMe, jstr); ... }</code>
Updated C Method
<code class="cpp">jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj, jint depth ){ jstring jstr = env->NewStringUTF("This string comes from JNI"); ... jstring result = env->CallObjectMethod(obj, messageMe, jstr); const char* str = env->GetStringUTFChars(result, NULL); printf("%s\n", str); ... }</code>
Conclusion
By addressing the object invocation and JNI signature mismatch issues, we can successfully call the messageMe() method from C code.
The above is the detailed content of How to Fix \'java.lang.NoSuchMethodError: messageMe\' When Calling Java Methods from C in Android?. For more information, please follow other related articles on the PHP Chinese website!