如何通过JNI创建HashMap <string,string =“”>然后解析为java

时间:2017-11-10 14:06:27

标签: java android android-ndk hashmap java-native-interface

您好我想通过Ndk保护我的网址和应用密钥,我想在应用中创建hashmap并静态存储键值然后解析为java,我按照 Stackoverflow 答案如Create HashMapJNI passing objects from C++ to Java从上面的链接中弃用了某些方法,但没有找到任何方法,我创建了HashMap但它给了我错误

#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;
}

错误

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)

2 个答案:

答案 0 :(得分:3)

我解决了我的问题我在代码中发现的主要问题是我错过了在 JNIEXPORT 行之后添加 JNICALL ,并且因为Key和val无效所以我改变了通过@Michael在上面的回答中提到的Java String C,现在代码工作正常,经过一些修改也改变了()

    #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;
        }

答案 1 :(得分:1)

keyval不是HashMap.put的有效参数。您需要从C字符串创建Java字符串,例如使用NewStringUTF