小弟在学习callback listener
参考这个
https://guides.codepath.com/android/Creating-Custom-Listeners#3-implement-listener-callback
练习的代码如下
MainActivity2.java
public class MainActivity2 extends AppCompatActivity {
Button button2;
TextView textView2;
DataListener listener;
public MainActivity2(){
this.listener=null;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
button2=findViewById(R.id.button2);
textView2=findViewById(R.id.textView2);
textView2.setText(String.valueOf(listener.getData()));
}
public interface DataListener{
int getData();
}
public void setDataListener(DataListener listener){
this.listener = listener;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button button;
private int x=5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button =findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i =new Intent();
i.setClass(MainActivity.this,MainActivity2.class);
startActivity(i);
finish();
}
});
MainActivity2 mainActivity2=new MainActivity2();
mainActivity2.setDataListener(new MainActivity2.DataListener() {
@Override
public int getData() {
return x;
}
});
}
}
目标只是想要让MainActivity2抓到 MainActivity中的x=5
可是执行之后
Caused by: java.lang.NullPointerException: Attempt to invoke interface method
'int bestfood.today.callbackdemo.MainActivity2$DataListner.getData()' on a
null object reference
总是报这行错误
常是几种写法
都报这个错误
有没有高手知道这个callback listener是哪里写错了?