gpt4 book ai didi

java - 自定义监听器为空

转载 作者:行者123 更新时间:2023-12-01 13:36:35 24 4
gpt4 key购买 nike

我在 Android 中使用了监听器,从未遇到过任何问题,但是今天当它尝试在 Java 中创建一个简单的监听器时,我收到 NullPointerException,这是什么原因以及如何修复它?

这包括 3 个类,ListenerMainStart.java、SendMessageClass.java 和 ReceiveMessageClass.java

ListenerMainStart.java

public class ListenerMainStart {

public static void main(String[] args) {

new SendMessageClass();

}
}

SendMessageClass.java

public class SendMessageClass {

public OnStringRequestedListener onStringListener;

public Timer timer;

public SendMessageClass() {

timer = new Timer();
timer.schedule(new TimerAction(), 3000);

}

public void SetOnStringRequestedListener(OnStringRequestedListener listener) {
System.out.println("value of onStringListener " + onStringListener.toString());
onStringListener = listener;

}

public interface OnStringRequestedListener {

public void passString(String sendString);

}

public class TimerAction extends TimerTask {

@Override
public void run() {

if (onStringListener!=null){
// pass string to other class, ONSTRINGLISTENER IS ALWASY NULL
onStringListener.passString("string sent from SendMessageclass");
} else {
System.out.println("onStringListener is null");
}

}

}

}

ReceiveMessageClass.java

public class ReceiveMessageClass implements SendMessageClass.OnStringRequestedListener {

SendMessageClass senderClass;

public ReceiveMessageClass() {

// instantiate class
senderClass = new SendMessageClass();

// set the listener to the class
senderClass.SetOnStringRequestedListener(this);

}

@Override
public void passString(String sendString) {

// do action when string is sent from other class
System.out.println("message recevied from other class is " + sendString);

}
}

最佳答案

看来您需要在打开计时器之前调用“SetOnStringRequestedListener”。事实上,该方法永远不会被调用,并且 onStringListener 永远不会被设置。您确实在接收器中调用了该行代码,但当然已经太晚了。您的 main 应该实例化接收者和发送者 SetOnStringRequestedListener,然后关闭计时器。

SendMessageClass send = new SendMessageClass();
ReceiveMessageClass recv = new ReceiveMessageClass()
send.SetOnStringRequestedListener(recv)

编辑:然后取出接收者中引用发送者的所有代码。使用监听器背后的想法是,这两个类并不直接了解彼此。

关于java - 自定义监听器为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21226046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com