问题
Hi I want to secure my web url and app secret keys through Ndk, I want to create hashmap
in app and also store key values statically then parse to java, I follow Stackoverflow answer like Create HashMap also JNI passing objects from C++ to Java some method deprecated from above link and didn't find any way to do this, I created HashMap
but it giving me error
#include <jni.h>
extern "C"
JNIEXPORT jobject
Java_com_company_project_home_ui_MainActivity_getUrlMap(
JNIEnv *env,
jobject /* this */) {
jclass mapClass = env->FindClass("java/util/HashMap");
if(mapClass == NULL)
{
return NULL;
}
jsize map_len = 1;
jmethodID init = env->GetMethodID(mapClass, "<init>", "(I)V");
jobject hashMap = env->NewObject(mapClass, init, map_len);
jmethodID put = env->GetMethodID(mapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
char *key = (char*)"URL_TEST_API" ;
char *val = (char*)"home.php";
env->CallObjectMethod(hashMap, put, key, val);
return hashMap;
}
Error
A/art: art/runtime/java_vm_ext.cc:410] native: #12 pc 00dd8f2f /data/app/com.company.project-1/oat/arm/base.odex (void com.company.project.home.ui.MainActivity.onCreate(android.os.Bundle)+714)
回答1:
I solved My Problem the main Problem I found in my code is I missed to add JNICALL after JNIEXPORT line, and as Key and val are not valid so I changed to Java String through C as mentioned by @Michael in above answer, now code working fine after some modification also change ()
#include <jni.h>
extern "C"
JNIEXPORT jobject
JNICALL
Java_com_company_project_somePackage_SplashScreen_getHashMap(JNIEnv *env, jobject /* this */) {
jclass mapClass = env->FindClass("java/util/HashMap");
if(mapClass == NULL)
{
return NULL;
}
jsize map_len = 1;
jmethodID init = env->GetMethodID(mapClass, "<init>", "(I)V");
jobject hashMap = env->NewObject(mapClass, init, map_len);
jmethodID put = env->GetMethodID(mapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
jenv->CallObjectMethod(hashMap, put, env->NewStringUTF("URL_TEST_API"), env->NewStringUTF("home.php"));
return hashMap;
}
回答2:
key
and val
are not valid arguments for HashMap.put
. You need to create Java strings from your C strings, e.g. using NewStringUTF.
来源:https://stackoverflow.com/questions/47224571/how-to-create-hashmapstring-string-through-jni-then-parse-to-java