简体   繁体   English

无法将 Java 代码集成到我的 React Native 项目中 - 错误:类型不兼容:ReactApplicationContext 无法转换为 Activity

[英]Unable to integrate java code to my react native project - error: incompatible types: ReactApplicationContext cannot be converted to Activity

I am trying to bridge java code with my react native project.我正在尝试将 Java 代码与我的本机项目连接起来。

My flow is this - when the user clicks on my pay button in react native, it routes to a page (which is a payment gateway) written in java and then when the user is done with the payment process it routes back to the initial page in react native.我的流程是这样的 - 当用户在 React Native 中点击我的支付按钮时,它会路由到一个用 Java 编写的页面(这是一个支付网关),然后当用户完成支付过程时,它会路由回初始页面在反应原生。 I am getting the error below:我收到以下错误:

HelloWorldModule.java:56: error: incompatible types: ReactApplicationContext cannot be converted
    to Activity
                                    new RavePayManager((Activity)reactContext).setAmount(Double.parseDouble(String.valueOf(amount)))

Please see below my code: //React native code to connect to java请看下面我的代码://React native code to connect to java

// We are importing the native Java module here
import {NativeModules} from 'react-native';
var HelloWorld = NativeModules.HelloWorld;

// type Props = {};
export default class App extends Component {

  // async function to call the Java native method
  async sayHiFromJava() {
    HelloWorld.sayHi( (err) => {console.log(err)}, (msg) => {console.log(msg)} );
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={ this.sayHiFromJava }>
              <Text>Invoke native Java code</Text>
         </TouchableOpacity>
      </View>
    );
  }
}

// MainApplication.java // 主应用程序.java

package com.packagename;

import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.RNFetchBlob.RNFetchBlobPackage;
import com.reactnativecommunity.geolocation.GeolocationPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import com.facebook.react.bridge.Callback;



public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost =
      new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
          // Packages that cannot be autolinked yet can be added manually here, for example:
          // packages.add(new MyReactNativePackage());
          packages.add(new HelloWorldPackage(MainApplication.this)); ---- // added payment gateway
          return packages;
        } 

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }
      };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }


  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
    initializeFlipper(this); // Remove this line if you don't want Flipper enabled
  }

  /**
   * Loads Flipper in React Native templates.
   *
   * @param context
   */
  private static void initializeFlipper(Context context) {
    if (BuildConfig.DEBUG) {
      try {
        /*
         We use reflection here to pick up the class that initializes Flipper,
        since Flipper library is not available in release mode
        */
        Class<?> aClass = Class.forName("com.facebook.flipper.ReactNativeFlipper");
        aClass.getMethod("initializeFlipper", Context.class).invoke(null, context);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
  }
}

// HelloWorldModule.java - payment gateway code // HelloWorldModule.java - 支付网关代码

package com.packagename;

import com.facebook.react.bridge.ReactApplicationContext;
import android.content.Context;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.uimanager.IllegalViewOperationException;
import com.flutterwave.raveandroid.RaveConstants;
import com.flutterwave.raveandroid.RavePayActivity;
import com.flutterwave.raveandroid.RavePayManager;
import android.app.Activity;

public class HelloWorldModule extends ReactContextBaseJavaModule {
    Context context;

 ReactApplicationContext reactContext;
    public HelloWorldModule(ReactApplicationContext reactContext,Context context) {
        super(reactContext); //required by React Native
        this.reactContext= reactContext;
          this.context= context;


    }

    @Override
    //getName is required to define the name of the module represented in JavaScript
    public String getName() { 
        return "HelloWorld";
    }

    @ReactMethod
    public void sayHi(Callback errorCallback, Callback successCallback) {
    //     try {
    //        System.out.println("Greetings from Java");

    //        successCallback.invoke("Callback : Greetings from Java");
    //    } catch (IllegalViewOperationException e) {
    //         errorCallback.invoke(e.getMessage());
    //     }
        try{
            int amount = 100;//call.argument("amount");
                        String narration = "Payment for soup";//call.argument("nara");
                        String countryCode = "NG"; //call.argument("countryCode");
                        String currency =  "NGN"; //call.argument("currency");
                        String amountText = "100";//call.argument("amountText");
                        String email = "haha@gmail.com";//call.argument("email");
                        String name = "King John";//call.argument("name");
                        String paymentId = "a98sjkhdjdu";//call.argument("paymentId");



                        String key ="*********-***********-X";
                         String secret = "*********-*********-X";

                                new RavePayManager((Activity)reactContext).setAmount(Double.parseDouble(String.valueOf(amount)))
                                .setCountry(countryCode)
                                .setCurrency(currency)
                                .setEmail(email)
                                .setfName(name)
                                .setlName("")
                                .setNarration(narration)
                                .setPublicKey(key)
                                .setTxRef(paymentId)
                                .acceptMpesaPayments(false)
                                .acceptAccountPayments(true)
                                .acceptCardPayments(true)
                                .acceptGHMobileMoneyPayments(false)
                                .onStagingEnv(false)
                                .initialize();
        } catch (IllegalViewOperationException e) {
            errorCallback.invoke(e.getMessage());
        }                  

    }

}

// HelloWorldPackage.java // HelloWorldPackage.java

package com.packagename;

import com.facebook.react.ReactPackage;
import android.content.Context;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.visioncapitaleye.HelloWorldModule;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HelloWorldPackage implements ReactPackage {
Context context;

    HelloWorldPackage(Context context) {
        this.context = context;
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<NativeModule> createNativeModules(
            ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        //this is where you register the module
        modules.add(new HelloWorldModule(reactContext,context)); // added HelloWorldModule
        return modules;
    }
}

I am new to java and cant seem to figure out what I am doing wrong.我是 Java 新手,似乎无法弄清楚我做错了什么。 Please assist.请协助。

I had a similar issue while trying to integrate a sdk into an existing react-native project.我在尝试将 sdk 集成到现有的 react-native 项目时遇到了类似的问题。 Try the following to see if it works for you.请尝试以下操作,看看它是否适合您。 Instead of casting reactContext into Activity, just get the current activity and use that.而不是将 reactContext 转换为 Activity,只需获取当前活动并使用它。

final Activity activity = getCurrentActivity();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:不兼容的类型:MainFragment 无法转换为 Activity - error: incompatible types: MainFragment cannot be converted to Activity JAVA 不兼容类型......“无法转换为” - JAVA incompatible types ... "cannot be converted to" 不兼容的类型:活动无法转换为 OnDateSetListener - incompatible types: Activity cannot be converted to OnDateSetListener 我的代码出现错误:不兼容的类型:int无法转换为布尔线:6 - I'm getting an error for my code: incompatible types: int cannot be converted to boolean line:6 JAVA不兼容类型:对象无法转换为我的类型 - JAVA incompatible types: Object cannot be converted to my type 编译Java程序后,它显示错误:不兼容的类型:double不能转换为double [] - After I compile my Java program, it says error: incompatible types: double cannot be converted to double[] 错误:类型不兼容:int无法转换为客户端-Java - error: incompatible types: int cannot be converted to Client - Java 错误:不兼容的类型:java.lang.String 无法转换为 String - error: incompatible types: java.lang.String cannot be converted to String Java错误:类型不兼容:LinkedList<diff> 不能转换成字符串</diff> - Error in Java: incompatible types: LinkedList<Diff> cannot be converted to String 错误:类型不兼容:java.lang.Object 无法转换为 E - Error: incompatible types: java.lang.Object cannot be converted to E
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM