Search code examples
javaandroidc++opencvjava-native-interface

Get String from JNI (OpenCV putText) to display in Java


I'm building an app that measures the distance between colored circles. I am able to do that but I want to save the measurement data (image) into a database (table in a new activity) that I am creating on Android but I don't know how to get the drawn String from the JNI to the activity that I'm creating for the database.

//put text
putText(mBgra, format("blue-green distance: %.2f cm ",conv3), Point(50,200), FONT_HERSHEY_SIMPLEX, 1, Scalar(0 , 255 , 0 , 255), 4);

How do I get the string from the code above and display it into a new java activity?


Solution

  • This shows how to pass the value into a textview on your activity.

    I assume that in

    JNIEXPORT void JNICALL Java_com_example_alexies_objecttrackertest_UBackTrackViewer_UBackObjectTrack (JNIEnv * env , jobject ubackObject,
        jint width , jint height, jbyteArray yuv, jintArray bgra, jboolean debug)
    

    UBackTrackViewer ubackObject is the activity you are asking about, and it defines the fields

    private TextView mBlueGreenDistance, mBlueYellowDistance, mMagentaRedDistance;
    

    You will probably initialize these fields to point to the actual text views in onCreate(), after you load the layout for your activity.

    Then in your JNI code you will have this initialization sequence (it's enough to run it once after the textview fields are initialized):

    jclass UBackTrackViewer_CLS = env->FindClass("com/example/alexies/objecttrackertest/UBackTrackViewer");
    jclass TextView_CLS = env->FindClass("android/widget/TextView");
    jmethodID setText_MID = env->GetMethodID(TextView_CLS, "setText", "(Ljava/lang/CharSequence;)V");
    
    jfieldID mBlueGreenDistance_FID = env->GetFieldID(UBackTrackViewer_CLS, "mBlueGreenDistance", "Landroid/widget/TextView;");
    …
    

    Now, empowered by these globals, you can add the following to your native method:

    jobject mBlueGreenDistance_OBJ = env->GetObjectField(ubackObject, mBlueGreenDistance_FID);
    jstring distance_STR = env->NewStringUTF(format("blue-green distance: %.2f cm", conv3).c_str());
    env->CallVoidMethod(mBlueGreenDistance_OBJ, setText_MID, distance_STR);
    

    No cleanup is necessary in this case. No memory or reference leaks will happen. Note that setText() method must be called from the UI thread.