繁体   English   中英

为什么我的 reactContext 变量仍然是 null?

[英]Why is my reactContext variable still null?

当我收到一条短信时,我正在尝试发送一条消息以做出本机反应。 我真的需要帮助,我不知道我做错了什么!

这是我创建的模块,用于管理发送事件以做出本机反应。

public class SendEventModule extends ReactContextBaseJavaModule implements ActivityEventListener {

    private static ReactApplicationContext reactContext;
    //private static ReactInstanceManager sReactInstanceManager = null;


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


    public SendEventModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
        reactContext.addActivityEventListener(this);
    }

    public static void test(String event, WritableNativeMap params) {
        Log.e("TEST_ERROR", "This is just a test");
        //final ReactContext context = sReactInstanceManager.getCurrentReactContext();
        sendEvent((ReactApplicationContext) reactContext, event, params);
    }

    private static void sendEvent(ReactApplicationContext reactContext,String event, WritableNativeMap params) {
        Log.e("TEST_ERROR", "we made it to send event");
        //context = (ReactApplicationContext) this.reactContext;
        //ReactContext currentContext = getReactApplicationContext();

        if(reactContext != null) {

            reactContext.getJSModule(RCTDeviceEventEmitter.class).emit(event, params);

        } else {
            try {
                reactContext.getJSModule(RCTDeviceEventEmitter.class).emit(event, params);
            }catch(Exception e) {
                Log.e("TEST_ERROR", e.getMessage());
            }
            Log.e("TEST_ERROR", "React Context is not defined");

        }

    }

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {}

    @Override
    public void onNewIntent(Intent intent){}


}

这是我的 SMS 接收器,我试图在其中发出我的事件以做出本机反应


public class SmsBroadcastReceiver extends BroadcastReceiver {

    private static ReactApplicationContext reactContext;

    public void onReceive(Context context, Intent intent) {

        Bundle intentExtras = intent.getExtras();
        Toast.makeText(context, "Message Received Bitch!", Toast.LENGTH_SHORT).show();

        //WritableMap params = Arguments.createMap();
        //params.putString("eventProperty", "someValue");

        WritableNativeMap params = new WritableNativeMap();
        params.putString("eventProperty", "someValue");


        try {
            SendEventModule.test("EventReminder", params);

        } catch (Exception e) {
         Log.e( "EVENT_ERROR", e.getMessage() );
        }


    }


}

这是我的错误,很明显没有定义 reactContext,我不知道为什么

2019-10-14 12:44:56.604 17861-17861/com.test E/TEST_ERROR: Attempt to invoke virtual method 'com.facebook.react.bridge.JavaScriptModule com.facebook.react.bridge.ReactApplicationContext.getJSModule(java. lang.Class)' 在 null object 参考

这是我的反应原生屏幕的代码

import React from "react";
import {
  Container,
  Header,
  Content,
  Textarea,
  Form,
  Button,
  Text,
  Left,
  Body,
  Right,
  Icon,
  Title,
  List,
  ListItem,
  Radio,
  CheckBox,
  Footer,
FooterTab,
Item,
Input } from "native-base";
import { GiftedChat } from 'react-native-gifted-chat';
import SendSMS from 'react-native-sms-x';
import { NativeEventEmitter, NativeModules, DeviceEventEmitter, TouchableOpacity, Image } from 'react-native';
import { Col, Row, Grid } from "react-native-easy-grid";
//import { setJSExceptionHandler, getJSExceptionHandler } from 'react-native-exception-handler';



class NewMessageScreen extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      messages: [],
      data: props.navigation.state.params.data
    };
  }

  componentDidMount() {

    this.setState({
      messages: [
        {
          _id: 1,
          text: 'Hello developer',
          createdAt: new Date(),
          user: {
            _id: 2,
            name: 'React Native',
            avatar: 'https://placeimg.com/140/140/any',
          },
        },
      ],
    });

    const eventEmitter = new NativeEventEmitter(NativeModules.SendEventModule);

    eventEmitter.addListener('EventReminder', (event) => {
       console.log(event.eventProperty); // "someValue"
    });


  }




  onSend(messages = []) {
    this.setState(previousState => ({
      messages: GiftedChat.append(previousState.messages, messages),
    }));

    SendSMS.send(1, this.state.data.number, messages[0].text,
      (msg)=>{
        alert(JSON.stringify(msg));
      }
    );

  }


  headerTitle() {
    //alert(JSON.stringify(this.state.data));
    if(this.state.data) {
      if (typeof this.state.data.displayName !== 'undefined') {
        return this.state.data.displayName;

      } else {
        return this.state.data.first_name + " " + this.state.data.last_name;
      }
    } else {
      return "Group Text";
    }
  }

  render() {
    return (
      <Container>
      <Header style={{ backgroundColor: '#234561'}} transparent>
        <Body>
          <Title style={{ justifyContent: 'center', width: '100%'}}>{ this.headerTitle() }</Title>
        </Body>
      </Header>

        <Row size={1} style={{ backgroundColor: "#234561" }}>
          <Col>
            <TouchableOpacity
               style={{
                   borderWidth:1,
                   borderColor:'rgba(0,0,0,0.2)',
                   alignItems:'center',
                   justifyContent:'center',
                   width:65,
                   height:65,
                   backgroundColor:'#fff',
                   borderRadius:50,
                   overflow: 'hidden',
                   poisition: 'absolute',
                   left: '50%',
                   marginLeft: -33,
                   top: '50%',
                   marginTop: -33,
                   elevation: 10
                 }}
             >
               <Image style={{ height: '100%', width: '100%'}} source={{ uri: 'https://icon-library.net/images/default-user-icon/default-user-icon-14.jpg' }} />
             </TouchableOpacity>
          </Col>
          <Col>
            <TouchableOpacity
               style={{
                   borderWidth:1,
                   borderColor:'rgba(0,0,0,0.2)',
                   alignItems:'center',
                   justifyContent:'center',
                   width:90,
                   height:90,
                   backgroundColor:'#fff',
                   borderRadius:50,
                   overflow: 'hidden',
                   left: '50%',
                   marginLeft: -45,
                   top: '50%',
                   marginTop: -45,
                   elevation: 10

                 }}
             >
               <Image style={{ height: '100%', width: '100%'}} source={{ uri: 'https://icon-library.net/images/default-user-icon/default-user-icon-14.jpg' }} />
             </TouchableOpacity>
           </Col>
          <Col>
            <TouchableOpacity
               style={{
                   borderWidth:1,
                   borderColor:'rgba(0,0,0,0.2)',
                   alignItems:'center',
                   justifyContent:'center',
                   width:65,
                   height:65,
                   backgroundColor:'#fff',
                   borderRadius:50,
                   overflow: 'hidden',
                   poisition: 'absolute',
                   left: '50%',
                   marginLeft: -33,
                   top: '50%',
                   marginTop: -33,
                   elevation: 10
                 }}
             >
               <Image style={{ height: '100%', width: '100%'}} source={{ uri: 'https://icon-library.net/images/default-user-icon/default-user-icon-14.jpg' }} />
             </TouchableOpacity>
          </Col>
        </Row>

        <Row size={4}>
          <GiftedChat
            messages={this.state.messages}
            onSend={messages => this.onSend(messages)}
            user={{
              _id: 1,
            }}
          />
        </Row>
      </Container>
    );
  }

}

export default NewMessageScreen;

请帮忙!!!

您的 SendEventModule 中有一个构造函数

public SendEventModule(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
    reactContext.addActivityEventListener(this);
}

但是您使用 static 访问权限调用您的方法,而无需先通过构造函数调用您的 SentEventModule。 在您的方法中,您尝试访问从未设置过的 reactContext。

在 Java 中,必须将变量设置为非 null。 例如

String text;
// text == null
text = "awesome";
// text == "awesome";

Maybe these two links will help you to solve your issues: https://gist.github.com/renganatha10/96ce8c845d981008d2a76da756954b25 How to access Activity from a React Native Android module?

进一步阅读 static: https://www.javatpoint.com/static-keyword-in-java

我通过注册模块解决了这个问题; 这发生在应用程序 package 的 createNativeModules 中。 如果一个模块未注册,它将无法从 JavaScript 获得,并且无法访问 ReactApplicationContext!!!


public class SendEventPackage implements ReactPackage {

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

    @Override
    public List<NativeModule> createNativeModules(
            ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();

        modules.add(new SendEventModule(reactContext));

        return modules;
    }

}

创建完成后,需要在 MainApplication.java 文件的 getPackages 方法中提供 package。

        @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 SendEventModule(this)); // THIS IS THE WRONG WAY
            packages.add(new SendEventPackage()); // <-- Add this line with your package name.

            return packages;
        }

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM