Search code examples
cencodingutf-8android-ndkjava-native-interface

JNI function returning illegal UTF characters at android


Im trying to return string from JNI to android but its returning illegal UTF characters like this:

JNI DETECTED ERROR IN APPLICATION: input is not valid Modified UTF-8:
illegal start byte 0x80
04-12 16:08:09.899 18210-18372 A/art:art/runtime/runtime.cc:427]
string: '���� ���!��"��,"���"���#���$��%���
%��`&��'��H(���)��D*���*��X+��,���,���-��4.��|.��P/��t/���/��01��x1��
2��D2���2���3���4���5��06���6��9���9��;���;��H<��=��0=���=���>��8?��

Here is the code which I am using:

JNIEXPORT jbyteArray Java_pakdata_com_qurantextc_MainActivity_get(
    JNIEnv *pEnv,
    jobject this,
    jint pageNo, jint lang) {


char* buffer=(char*)malloc(10000);  // this buffer contains the ayat
register unsigned int pageNumber = pageNo - 1;

char * header=(char*)malloc(1000);
sprintf(header,"[{\"OFFSET\":%d,\"DATA\":\"",pageNumber+1);
strcpy(buffer,header);

// to get the last ayat of the page
// this loop will fetch all ayats of the page

for (int i = start_ayat; i <= end_ayat; i++) {



sprintf(buffer+strlen(buffer),"<div class=\\\"qr0\\\" data-ayat=\\\"%d\\\" id=\"%d\\\"><span>",i+1,i+1);
get(lang, i, buffer + strlen(buffer)); // len is equal to length of buffer (   strlen()  )
        strcpy(buffer+strlen(buffer),"<\\/span><\\/div>");


}
  // char* footer;
sprintf(buffer+strlen(buffer),"<div class=\\\"pagebreak\">%d<a id=\\\"%d\\\"next\\\"href=\\\"\\/page\\/%d\\\"></a><\\/div <\\/div>\"}]",pageNumber+1,pageNumber+1,pageNumber+1);

__android_log_print(ANDROID_LOG_DEBUG, "LOG_TAG","string: '%s'" , buffer);
int l = strlen(buffer);
char c[l];
strcpy(c,replace(buffer,"\r","<br>"));

jbyteArray ret = (*pEnv)->NewByteArray(pEnv,l);
(*pEnv)->SetByteArrayRegion (pEnv,ret, 0, l, c);
const char * errorKind = NULL;
uint8_t utf8 = checkUtfytes(c, &errorKind);
if  (errorKind != NULL) {
    free(buffer);
    return ret;

} else {
    free(buffer);
    return ret;
}

I have tried using this too:

return = (*pEnv)->NewStringUTF(pEnv,buffer)

but it still contain illegal UTF characters..

Here is my android side code

byte[] ss = get(a, pos);
s= new String(ss,"UTF-8");

Still getting illegal UTF character error. I have tried encoding on java side but its no help either, I am posting here because all other methods that are written here i have already tried but it didn't worked.

PLEASE HELP!!!


Solution

  • May be I am late but your code seems to be correct but according to JNI documentation they doesn't support these characters. You have to handle it from server side. Hope it helps.