JNI Android – Converting char* to byte array and return it to java

I initially used a function to return a char* to java as UTF-8 string, but since I kept getting errors, I wrote the following function to return a char* as a Java byte[], so that I could try to convert the array into a String in java side:

jbyteArray Java_com_vektor_amapper_util_InputDeviceManager_getDevNameBytes(JNIEnv* env, jobject thiz, jint index) {
    if(pDevs[index].device_name == NULL) return NULL;
    int n=0;
    while(pDevs[index].device_name){
        n++;
    } if (n==0) return NULL;
    jbyteArray arr = (*env)->NewByteArray(env, n);
    (*env)->SetByteArrayRegion(env,arr,0,n, (jbyte*)pDevs[index].device_name);
    return arr;
}

But when I call it my application crashes. Am I missing something?

  • How to draw a circle inside a circle using Android xml shapes?
  • Android: Image over image
  • IntelliJ Idea auto create new method
  • Get SHA1 fingerprint certificate in Android Studio for Google Maps
  • How to get a Uri object from Bitmap
  • Is it possible to get the HTML code from WebView
  • Update: The condition was missing a ++ and this caused an infinite loop. But now with the following code:

    jbyteArray Java_com_vektor_amapper_util_InputDeviceManager_getDevNameBytes(JNIEnv* env, jobject thiz, jint index) {
        int n=0;
        if(pDevs[index].device_name == NULL) return NULL;
        while(pDevs[index].device_name++){
            n++;
        } if(n==0) return NULL;
            jbyteArray arr = (*env)->NewByteArray(env, n);
            (*env)->SetByteArrayRegion(env,arr,0,n, (jbyte*)pDevs[index].device_name);
            return arr;
    }
    

    I get this weird JNI warning:

    06-15 22:40:02.303: W/dalvikvm(7616): JNI WARNING: negative jsize (NewByteArray)

    How can it be since I am only increasing the value of n?

    Update 2: the following code works:

    jbyteArray Java_com_vektor_amapper_util_InputDeviceManager_getDevNameBytes(
            JNIEnv* env, jobject thiz, jint index) {
    
        if(pDevs[index].device_name == NULL) return NULL;
        int n=0;
        char* p = pDevs[index].device_name;
        while(*p++){
            n++;
        } if(n<=0) return NULL;
        jbyteArray arr = (*env)->NewByteArray(env, n);
        (*env)->SetByteArrayRegion(env,arr,0,n, (jbyte*)pDevs[index].device_name);
    
        return arr;
    }
    

    Related posts:

    ADT 22.3 (android 4.4) - getting error &ldquo;After scene creation, #init() must be called&r...
    Use firefox as render engine for Android webview
    StaggeredGridLayoutManager reorders items
    How do i order my SQLITE database in descending order, for an android app?
    onClick listener to a ListView Image - Android
    How to enable AutoStart option for my App in Xiaomi phone Security App programmatically in android
    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.