这是我的情况:
我想让两个班级相互沟通。所以MainActivity是 制作SomeOtherstrangeClass的新对象。
public class MainActivity extends AppCompatActivity implements myEventListener {
private TextView txtHelloSet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtHelloSet = (TextView) findViewById(R.id.txtHello);
SomeOtherStrangeClass someOtherStrangeClass = new SomeOtherStrangeClass();
}
@Override
public void someEvent(int e) {
Log.v("[Listener]", "SomeEvent triggered. Number: " + e);
txtHelloSet.setText("Event came in!");
}
}
#
public class SomeOtherStrangeClass {
public SomeOtherStrangeClass(){
EventThrower eventThrower = new EventThrower();
MainActivity mainActivity = new MainActivity();
eventThrower.addListener(mainActivity);
Log.v("[Listener]", "Throwing event");
eventThrower.someEvent(13);
}
}
interface myEventListener extends java.util.EventListener {
void someEvent(int e);
}
public class EventThrower {
private List<myEventListener> listeners = new ArrayList<myEventListener>();
public void addListener(myEventListener toAdd){
listeners.add(toAdd);
}
public void removeListener(myEventListener toRemove){
listeners.remove(toRemove);
}
public void someEvent(int e){
for(myEventListener el : listeners)
el.someEvent(e);
}
}
所以这就是我这样做的方式。但问题是,当一个事件被抛出时,它仍然会调用Methode someEvent,它位于SomeOtherStrangeClass的MainActivity中。所以我无法修改MainActivity中的任何对象。就像他们不存在一样。我正在接受NPE:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
为什么会这样? 对此有什么解决方案吗?
答案 0 :(得分:1)
MainActivity mainActivity = new MainActivity();
你这里做错了什么。它不应该像这样创建Activity对象。您应该重新考虑您的应用程序逻辑。
答案 1 :(得分:0)
您需要引用当前位于前台的MainActivity
实例,以便识别其中的任何回调。
尝试更改SomeOtherStrangeClass
的构造函数,如下所示:
public SomeOtherStrangeClass(myEventListener listener) {
EventThrower eventThrower = new EventThrower();
eventThrower.addListener(listener);
Log.v("[Listener]", "Throwing event");
eventThrower.someEvent(13);
}
然后,在你活动的onCreate()中,
SomeOtherStrangeClass someOtherStrangeClass = new SomeOtherStrangeClass(this);