Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call java class methods from react-native (not Android Activity java class)

Actually I am new here for react-native application development. And I am trying to develop a small react-native application with database connectivity (AWS Dynamo db). I select a java as a server side language. And I want to know, is there any possible to import java classes in react-native (i.e. accessing java methods from react-native).

Thanks.

like image 805
ajith kumar Avatar asked Apr 19 '18 09:04

ajith kumar


People also ask

Can I use Java with React Native?

Since React Native is just a wrapper for native components, there's nothing stopping you from adding native Java or Swift code where you need it.

Where is MainActivity Java in React Native?

This file is located in android/app/src/main/java/com/<yourproject>/MainActivity. java .


1 Answers

Yes, you can, with a bit of glue code. React Native has a concept of Native Modules that allows you to interface with any Java code.

Once you've created your native module according to the above linked instructions, you can decorate any method on the module with a @ReactMethod annotation to make it available in JavaScript:

public class YourDynamoDBModule extends ReactContextBaseJavaModule {

  // ...
  @ReactMethod
  public void arbitraryMethod(string query, Promise promise) {
      // do something with your third-party library
        Promise.resolve(yourResponse);
  }
  //...
}

You'll need a bit more boilerplate than that (it's all explained in the docs). Once that is in place, you can call it from JavaScript like follows:

import { NativeModules } from 'react-native';

NativeModules
  .YourDynamoDBModule
  .arbitraryMethod('...')
  .then(result => {

  });

It's worth noting that all native module calls are inherently asynchronous, so if you need to pass data back to JavaScript you need to use promises (as above) or callbacks.

like image 85
jevakallio Avatar answered Oct 08 '22 07:10

jevakallio