Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create HashMap<String, String> through JNI then parse to java

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)
like image 399
Hussain Sherwani Avatar asked Jan 29 '23 06:01

Hussain Sherwani


2 Answers

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;
        }
like image 185
Hussain Sherwani Avatar answered Jan 31 '23 19:01

Hussain Sherwani


key and val are not valid arguments for HashMap.put. You need to create Java strings from your C strings, e.g. using NewStringUTF.

like image 43
Michael Avatar answered Jan 31 '23 20:01

Michael