Create a C++ class and Use that class In Another C++ Class Which contain JNI methods in ndk android

Amjad Khan 07/27/2017. 1 answers, 51 views
android android c++ android-ndk android-ndk native

In Android, I am facing issues in connecting two cpp class in native Android. I have tested with the single class it working fine.

but when I have created another file and now facing an issue in linking it with current cpp file.

MainClass.cpp

#include <jni.h>
#include "native-handler.h"

extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_fragment_SampleFragment_setTitle(JNIEnv *env,jobject instance,jobject context) {

    ClassNativeHandler classNativeHandler;
    return classNativeHandler.getType(env,context);
}

native-handler.cpp

#include <jni.h>
#include "native-handler.h"

jstring jstringObject;

jstring ClassNativeHandler::getType(JNIEnv *env, jobject contextObject) {
    jstring jstringObject = env->NewStringUTF("Hello world");
    return jstringObject;
}

void ClassNativeHandler::setType(jstring string) {
    myType = string;
    jstringObject = string;
}

native-handler.h

#ifndef SAMPLE_NATIVE_HANDLER_H
#define SAMPLE_NATIVE_HANDLER_H

#include <iostream>
#include <string>

class ClassNativeHandler
{
private:
    jstring myType;

public:
    void setType(jstring string);
    jstring getType(JNIEnv *env, jobject contextObject);
    jstring getHeaderName(JNIEnv *env);

};

#endif //SAMPLE_NATIVE_HANDLER_H

Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE := Native
LOCAL_SRC_FILES := ../cpp/mainClass.cpp
LOCAL_C_INCLUDES := ../cpp/native-handler.h
LOCAL_LDLIBS := -lz -llog -ljnigraphics
include $(BUILD_SHARED_LIBRARY)

Error : undefined reference to `ClassNativeHandler::getType(_JNIEnv*, _jobject*)'

on this linereturn classNativeHandler.getType(env,context);

So I am not able to build the .so file. Please guide me

1 Comments
Joe C 07/27/2017
What does this question have to do with Java?

1 Answers


taskinoor 07/27/2017.

You haven't compiled native-handler.cpp. You need to specify it in LOCAL_SRC_FILES so that NDK compiles it.

LOCAL_SRC_FILES := ../cpp/mainClass.cpp ../cpp/native-handler.cpp

3 comments
Amjad Khan 07/27/2017
Now I can Compile the file, But get error on running the application like { JNI DETECTED ERROR IN APPLICATION: use of deleted local reference 0x7f5bc55a3d }
taskinoor 07/27/2017
Inside ClassNativeHandler::getType you have defined local jstring jstringObject effectively shadowing the global jstringObject that might cause the invalid local reference error.
Amjad Khan 07/27/2017
It is not stored in the memory when pointing again to the location getting null so getting error on ClassNativeHandler::getType Which is using locai variable jstring jstringObject

Related questions

Hot questions

Language

Popular Tags