我已经使用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);
}
}
答案 0 :(得分:0)
在打开定时器之前,您似乎需要调用“SetOnStringRequestedListener”。实际上,该方法永远不会被调用,并且onStringListener永远不会被设置。你确实在接收器中调用了那行代码,但当然在那里为时已晚。你的主要应该立即同步接收者和发送者,SetOnStringRequestedListener,然后设置定时器。
SendMessageClass send = new SendMessageClass();
ReceiveMessageClass recv = new ReceiveMessageClass()
send.SetOnStringRequestedListener(recv)
编辑:然后取出接收器中引用发件人的任何代码。使用监听器的想法是这两个类不直接相互了解。