How to pass parameters into Java method using QAndroidJniObject

452 Views Asked by At

In my Qt app, if I have a method written in Java inside my MainActivity class like below,

public Boolean myJavaTestMethod() {
    return true;
}

I know that I can invoke the method in the following way:

QAndroidJniObject method_retval = QtAndroid::androidActivity().callObjectMethod<jboolean>("myJavaTestMethod");

Question:
Above is great and it works. But, how do I pass a string from Qt C++ side into myJavaTestMethod?

Lets say I want to call the below method which takes an input parameter String into it

public Boolean myJavaTestMethodWithParam(String str) {
    return true;
}

Environment:
I am using Qt 5.15.1 commercial version.

1

There are 1 best solutions below

4
On

You have to take the following steps:

  1. Call your Java object's function using name and signature:
QAndroidJniObject result = activity.callObjectMethod("myJavaTestMethodWithParam", "(Ljava/lang/String;)B", myJString);

Where activity is just what QtAndroid::androidActivity() returns, myJavaTestMethodWithParam your activity function and "(Ljava/lang/String;)B" is its signature.

  1. Turn your QString into a jstring:
QString helloString("Hello");

QAndroidJniObject string = QAndroidJniObject::fromString(helloString);
jstring myJString = string.object<jstring>();

To understand the signature part, check: https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html#wp16432

More on calling Android/Java methods here: https://doc.qt.io/qt-5/qandroidjniobject.html#callObjectMethod-1