Home >Backend Development >C++ >Why am I getting a \'NoSuchMethodError\' when calling a Java method from C in Android?

Why am I getting a \'NoSuchMethodError\' when calling a Java method from C in Android?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 21:23:291036browse

Why am I getting a

Calling a Java Method from C in Android: Overcoming Java Exceptions

In Android development, calling a Java method from C can be straightforward. However, you may encounter the "NoSuchMethodError" exception if you're not careful.

The Java Code

Let's start by examining the Java code:

<code class="java">public class MainActivity extends Activity {
    //...

    public void messageMe(String text) {
        System.out.println(text);
    }

    //...
}</code>

This code defines a method called "messageMe" that takes a string as an argument.

The C Code

Now, let's look at the C code that attempts to call "messageMe":

<code class="cpp">jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj, jint depth ){
    //...

    // Get the method that you want to call
    jmethodID messageMe = env->GetMethodID(clazz, "messageMe", "(Ljava/lang/String;)V");

    //...

    jobject result = env->CallObjectMethod(jstr, messageMe);
    //...
}</code>

In this code, the issue lies in the "CallObjectMethod" function. This method requires the "obj" parameter to be the object on which the method is being called. However, in the given code, it's using "jstr" instead, which is the string being passed to the method.

The Solution

To fix this, you need to pass the correct object as the first argument to "CallObjectMethod":

<code class="cpp">jobject result = env->CallObjectMethod(obj, messageMe, jstr);</code>

Additionally, since "messageMe" is a void method, you should call "CallVoidMethod" instead of "CallObjectMethod". Also, remember to change the JNI signature and Java code to match the new return type.

The above is the detailed content of Why am I getting a \'NoSuchMethodError\' when calling a Java method from C in Android?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn