Search code examples
androidc++qtjava-native-interfaceqtandroidextras

Calling simple java static method via JNI does not work, though c++ compiles and run it


Considering this Java class with the static method:

public class TestClass{
    public string str;
    public TestClass() {
        str = "Test From Java";
    }
    public static String staticMethod() {
        return "Test From Java";
    }
}

I have written these lines of code in c++ file:

QAndroidJniObject str =  QAndroidJniObject::callStaticObjectMethod(
                                   "org/.../TestClass"
                                   ,"staticMethod"
                                   ,"(V)Ljava/lang/String;");

It seems everything is working but I don't know how can I use the str Object. I tried to convert it to a QString object using str.tostring() method but it always returns an empty string. Why it does not work as expected? I've also tested ()Ljava/lang/String; for method signature but no success!
Thanks in advance.


Solution

  • You should specify the returned JNI type in <...> when calling the method :

    QAndroidJniObject str =  QAndroidJniObject::callStaticObjectMethod<jstring>(
                                   "org/.../TestClass"
                                   ,"staticMethod");
    
    QString string = str.toString();
    

    Here there is no need to define the signature since your function has no argument.