The functions all get called. The call to myFunctionB returns a boolean.
But the call to myFunctionC returns an empty array no matter what I put in the Java code.
Does AndroidJavaObject.Call() not work when returning arrays? Is there some special processing required?
This seems to be an issue with little knowledge, so I thought I would reply even though this thread is quite old.
The problem is that an array is not a native type, so you can’t do what you are trying in the example. Arrays, as far as I can tell, must always be transferred in the form of an Object. The Unity JNIHelper class offers a method (ConvertFromJNIArray()) to change an AndroidJavaObject into a .NET array. The array has to be an array of native types from what I can tell (except string, which isn’t native, but it still works). There is also a ConvertToJNIArray that you can use to send an array to the Java side. Hopefully the code below will shed some light on it.
C# code:
AndroidJavaClass cls = new AndroidJavaClass("com.mycompany.myproduct.myclass");
AndroidJavaObject obj = cls.CallStatic<AndroidJavaObject>("getStringArray");
if (obj.GetRawObject().ToInt32() != 0)
{
// String[] returned with some data!
String[] result = AndroidJNIHelper.ConvertFromJNIArray<String[]>
(obj.GetRawObject());
foreach (String str in result)
{
// Do something with the strings
}
}
else
{
// null String[] returned
}
obj.Dispose();
cls.Dispose();
java code:
public static String[] getStringArray()
{
String[] strs = { "Test1", "Test2" };
return strs; // Or alternatively, return null;
}
Pay special attention to checking for null by using the obj.GetRawObject().ToInt32() method and testing it for 0. obj itself will not be null as it is a valid object, but if you call ConvertFromJNIArray(obj) with the obj’s Raw Object value of 0, it will crash.
// Create a java.lang.String object holding the string "some string",
// and retrieve it's hash code.
function Start() {
var jo = new AndroidJavaObject("java.lang.String", "some string");
var hash = jo.Call.<int>("hashCode");
}
Modified version, to return an array:
function Start() {
var jc = new AndroidJavaClass ("com.test.test");
var doubleArary = jc.Call.<double[]>("getDoubleArray");
}