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

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

Barbara Streisand
Release: 2024-11-03 15:30:03
Original
556 people have browsed it

Why am I getting a

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template