0

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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Can you please add the code for how you got the activity object?
Oh, that's just as you did, QtAndroid::androidActivity(), I just left it out to save space.
This doesn't work. I think this answer is wrong. How can activity.myJavaTestMethodWithParam compile?
I just saw what you said, I fixed it, myJavaTestMethodWithParam won't compile obviously, that's the method you want to call, it goes as the first argument of callObjectMethod(...). A mistake typing in the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.