使用Unity AndroidJavaObject创建java hashmap

时间:2017-07-11 12:32:57

标签: unity3d xamarin.android mono unity5 unityscript

我的java库中有一个方法,它将Map作为输入。
这是我的java方法

public void myMethod(Map<String, String> map){
    //do some thing with this map
}

我在Unity中的C#代码

AndroidJavaObject javaMap= new AndroidJavaObject("java.util.HashMap");
javaMap.Call("put", "key1", "value1");
AndroidJavaClass javaClass = new AndroidJavaClass("com.alirezaahmadi.android.sdk.core.BaseAPI");
javaClass.CallStatic("myMethod", javaMap);

我可以尝试这样的代码,但Map是一个泛型类,这段代码不起作用

当我运行此操作时,我收到此错误

AndroidJavaException: java.lang.NoSuchMethodError: no non-static method with name='put' signature='(Ljava/lang/String;Ljava/lang/String;)V' in class Ljava.lang.Object;
java.lang.NoSuchMethodError: no non-static method with name='put' signature='(Ljava/lang/String;Ljava/lang/String;)V' in class Ljava.lang.Object;

我如何解决此问题并将java hashmap路径化为此方法。顺便说一下,我无法改变java代码。

2 个答案:

答案 0 :(得分:1)

经过几个小时的尝试后,我发现这段代码将我的C#dictainary转换为AndroidJavaObject HashMap

public static AndroidJavaObject CreateJavaMapFromDictainary(IDictionary<string, string> parameters)
{
    AndroidJavaObject javaMap = new AndroidJavaObject("java.util.HashMap");
    IntPtr putMethod = AndroidJNIHelper.GetMethodID(
        javaMap.GetRawClass(), "put",
            "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");

    object[] args = new object[2];
    foreach (KeyValuePair<string, string> kvp in parameters)
    {

        using (AndroidJavaObject k = new AndroidJavaObject(
            "java.lang.String", kvp.Key))
        {
            using (AndroidJavaObject v = new AndroidJavaObject(
                "java.lang.String", kvp.Value))
            {
                args[0] = k;
                args[1] = v;
                AndroidJNI.CallObjectMethod(javaMap.GetRawObject(),
                        putMethod, AndroidJNIHelper.CreateJNIArgArray(args));
            }
        }
    }

    return javaMap;
}

然后我只需调用我的方法并将路径称为

AndroidJavaObject javaMap = CreateJavaMapFromDictainary(myDictainry);
AndroidJavaClass javaClass = new AndroidJavaClass("com.alirezaahmadi.android.sdk.core.BaseAPI");
javaClass.CallStatic("myMethod", javaMap);

答案 1 :(得分:0)

这是我使用的Reza解决方案的简化版本:

public AndroidJavaObject ConvertDictionaryToJavaMap(Dictionary<string, string> dictionary) {

    AndroidJavaObject map = new AndroidJavaObject("java.util.HashMap");
    IntPtr putMethod = AndroidJNIHelper.GetMethodID(map.GetRawClass(), "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
    foreach (var entry in dictionary) {
        AndroidJNI.CallObjectMethod(
            map.GetRawObject(),
            putMethod,
            AndroidJNIHelper.CreateJNIArgArray(new object[] { entry.Key, entry.Value })
        );
    }
    return map;
}