Pages

getteammates.com

Friday, 12 June 2015

Setting fields of an android java object from unity C#, including array

Lets say we want to set fields of a Java object in Unity with different types, including array.

Let the class in java be,
package com.example; 

public class Address {
 int mHouseNumber;
 String mStreet;
 String mCity;
 String mCountry;
 String [] mPhoneNumders;
}

Now lets create Address object from c# and populate its fields.
First of all lets create an Address object
AndroidJavaObject addressObj = new AndroidJavaObject ("com.example.Address");

Now populate all the fields except the mPhoneNumders.
addressObj.Set<int> ("mHouseNumber", 10);
addressObj.Set<string> ("mStreet", "abc");
addressObj.Set<string> ("mCity", "def");
addressObj.Set<string> ("mCountry", "ghi");

Now lets create a java object from the c# array so that we can set the field mPhoneNumders. Lets create a small method for it.
private AndroidJavaObject javaArrayFromCS(string [] values) {
    AndroidJavaClass arrayClass  = new AndroidJavaClass("java.lang.reflect.Array");
    AndroidJavaObject arrayObject = arrayClass.CallStatic<AndroidJavaObject>("newInstance",
                                             new AndroidJavaClass("java.lang.String"),
            values.Count());
 for (int i=0; i<values.Count(); ++i) {
     arrayClass.CallStatic("set", arrayObject, i,
                               new AndroidJavaObject("java.lang.String", values[i])));
 }
}

Now as the last step lets set the field mPhoneNumders
string [] phoneNumbers = {"12345678", "87654321"};
addressObj.Set<AndroidJavaObject> ("mPhoneNumders", javaArrayFromCS(phoneNumbers));