androidreact-nativereact-native-bridge

pass an arraylist of custom objects to react native side from android


I have a list of custom objects (List) . I need to send this data to React Native side to display in flat list . How do i do this ?This list is present in

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


Solution

  • Since you would like to send an ArrayList, you would have to send a WritableArray from the native side to react-native.

    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);
      }
    }
    

    On the react-native side, you can create a javascript module for your native module as follows:

    import { NativeModules } from "react-native";
    module.exports = NativeModules.NativeToReactModule;
    

    You can then access the ArrayList you sent from the native side.

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

    NOTE: The answer does not show a complete setup for making use of a native module.