Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from Android native - Kotlin to React Native?

I am new to the React Native integration in Android. I am creating a chat application and for that need to pass the UserId and another User information in my React Native component. How can I pass that from Android Native? I searched but I haven't found any successful lead. I tried doing it with SharedPreference, But didn't have any idea how to extract the sharedpreference holder in the React native. Are there any other way that I can extract this information?

I have created ReactRootView in the ReactActivity and integrated ReactInstanceManager in it.

As per Geng's and Cool7's answer, I have implemented my Android Kotlin code as given below:

val map = Arguments.createMap()
    map.putString("user_id", "Value1")
    try {
        mReactInstanceManager?.currentReactContext
                ?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
                ?.emit("userEventMap", map)
    } catch (e: Exception) {
        Log.d("ChatActivity", "DeviceEventEmitter Caught Exception: " + e.printStackTrace())
    }

And my React native code to extract it is as below:

componentWillMount() {
console.log("UserId Emission");
DeviceEventEmitter.addListener("userEventMap", function() {
  console.log("UserId Emission inside");
  console.log("UserId :: ", e.user_id);
});

}

I have tried Cool7's ditto code also and like above also. But UserId Emission is getting printed but the inside logs are not. The Map is not getting listened in this emitter.

Thanks in advance.

like image 299
Siraj Sumra Avatar asked Nov 30 '25 16:11

Siraj Sumra


1 Answers

To send data from android to react native :

From android side emit your event(Notification or Broadcast) in following way:

    public class MainActivity extends ReactActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        WritableMap map = Arguments.createMap();
        map.putString("key1", "Value1");
   map.putString("key1", "Value1");

        try {
          getReactInstanceManager().getCurrentReactContext()
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit("customEventName", map);
        } catch (Exception e){
          Log.e("ReactNative", "Caught Exception: " + e.getMessage());
        }
    }

And in react component addEventListner(subscribe) to that event like as:

import { DeviceEventEmitter } from 'react-native';

componentWillMount: function() {
  DeviceEventEmitter.addListener('customEventName', function(e: Event) {
    // handle event.
  });

}

Also refer

To send data from android native to react native

like image 193
Bhagwat K Avatar answered Dec 02 '25 06:12

Bhagwat K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!