Im trying to create a 1D jobjectArray. When printing from inside the loop, "args" array prints correct values but once it is out of the loop, only the last element gets printed repeatedly.
This is "args" jobjectArray declaration:
//Declare an object array
jobjectArray args;
//Get the class of the object, generally ava/lang/Object is enough
jclass objClass = (*env)->FindClass(env,"java/lang/Object");
//New object array
args = (*env)->NewObjectArray(env,unum, objClass, 0);
This is the loop used to insert values into the jobjectArray: ( rec_msg[] struct array has correct values and there are no problems creating or inserting a jobject)
for(int i=0; i < unum; i )
{
printf("\ni-%d---", i);
(*env)->SetShortField(env,obj,stat,1);
(*env)->SetShortField(env,obj,fnumber,rec_msg[i].filenum );
str = (*env)->NewStringUTF(env, rec_msg[i].username);
(*env)->SetObjectField(env,obj,user, str);
(*env)->SetObjectArrayElement(env,args, i, obj);
printf("args fnum%d\n", (*env)->GetShortField(env, (*env)->GetObjectArrayElement(env, args, i), fnumber));
}
The printf in here prints the values of fnum (a field in jobject) correctly as:
i-0-args fnum3
i-1-args fnum2
i-2-args fnum9
but after the lopp, I wrote a new simple loop as:
for(int i=0; i < unum; i )
{
printf("\ni-%d ARGS fnum%d",i, (*env)->GetShortField(env, (*env)->GetObjectArrayElement(env, args, i), fnumber));
}
this prints:
i-0 ARGS fnum9
i-1 ARGS fnum9
i-2 ARGS fnum9
ie the last object repeats. There are no statements between this loop and the previous. Im unable to know why the "args" jobjectrray repeats the last element when it prints fine inside the first loop. Please let me know if any other details are required.
CodePudding user response:
You populate your array with three refetences to the same object. In the first loop the values of obj are changing on each iteration, that's why you get different values printed. Try to add the printing command
printf("\ni-%d ARGS fnum%d",0,(*env)->GetShortField(env, (*env)->GetObjectArrayElement(env, args,0), fnumber));
as the last sentence in the first loop. You'll see that the value of the first element of the array is being updated on each iteration, because it's still referencing the same object.