gpt4 book ai didi

android - 传递自定义对象的数组列表以从 android 响应 native 端

转载 作者:行者123 更新时间:2023-12-04 23:47:45 34 4
gpt4 key购买 nike

我有一个自定义对象列表 (List) 。我需要将此数据发送到 React Native 端以显示在平面列表中。我该怎么做?这个列表出现在

类 NativeToReact(reactContext:ReactApplicationContext,userManager:IUserManager):ReactContextBaseJavaModule(reactContext)`

最佳答案

由于您想发送 ArrayList ,您必须发送 WritableArray从原生端到 react 原生端。

public class NativeToReactModule extends ReactContextBaseJavaModule {

public NativeToReactModule(ReactApplicationContext reactContext) {
super(reactContext);
}

@Override
public String getName() {
return "NativeToReactModule";
}

private static WritableMap convertJsonToMap(JSONObject jsonObject) throws JSONException {
WritableMap map = new WritableNativeMap();

Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
map.putMap(key, convertJsonToMap((JSONObject) value));
} else if (value instanceof Boolean) {
map.putBoolean(key, (Boolean) value);
} else if (value instanceof Integer) {
map.putInt(key, (Integer) value);
} else if (value instanceof Double) {
map.putDouble(key, (Double) value);
} else if (value instanceof String) {
map.putString(key, (String) value);
} else {
map.putString(key, value.toString());
}
}
return map;
}

@ReactMethod
public void returnArrayOfObjects(Callback successCallback) throws JSONException {
List<CustomObject> aList = new ArrayList<CustomObject>();
Gson g = new Gson();

aList.add(new CustomObject("Nameone", 1));
aList.add(new CustomObject("nametwo", 132));

WritableArray array = new WritableNativeArray();
for (CustomObject co : aList) {
JSONObject jo = new JSONObject(g.toJson(co));
WritableMap wm = convertJsonToMap(jo);
array.pushMap(wm);
}

successCallback.invoke(array);
}
}

在 react-native 方面,您可以为您的 native 模块创建一个 javascript 模块,如下所示:
import { NativeModules } from "react-native";
module.exports = NativeModules.NativeToReactModule;

然后您可以访问 ArrayList您从本地发送。
import NativeToReact from "./NativeToReactModule";

...
...
...

NativeToReact.returnArrayOfObjects(array => {
console.log(array, "The array you sent from the native side");
});

注意 :答案没有显示使用 native 模块的完整设置。

关于android - 传递自定义对象的数组列表以从 android 响应 native 端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54336367/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com