Call Java methods from C++ in Qt
I’m trying to call a method defined in android activity in c++ qt using QAndroidJniObject.
Here is my call in a C++ class
QAndroidJniObject data = QAndroidJniObject::callStaticObjectMethod("com/android/app/appActivity",
"appData",
"(I)Ljava/lang/String;" );
QString dataValue = data.toString();
qDebug() <<"Data is " << dataValue;
This appData is defined in the appActiviy android class and returns a string
This is the defined method I want to call and get the returned string value
static String appData(){
Log.d("App Data is ", "Working");
return data;
}
But what I get is null is dataValue and it doesn’t throw any error either.
Solution
You may need to manually check for exceptions for Java errors.
From Qt documentation:
Handling Java Exception
When calling Java functions that might throw an exception, it is important that you check, handle and clear out the exception before continuing.
Note: It is unsafe to make a JNI call when there are exceptions pending.
void functionException()
{
QAndroidJniObject myString = QAndroidJniObject::fromString("Hello");
jchar c = myString.callMethod<jchar>("charAt", "(I)C", 1000);
QAndroidJniEnvironment env;
if (env->ExceptionCheck()) {
Handle exception here.
env->ExceptionClear();
}
}
Are you sure you want to call com/android/app/appActivity instead of com/android/app/
activity
?