我很难弄清楚为什么我在接收它的方法中分配它时,我的全班级变量为空。我曾尝试阅读有关变量,对象等的引用之间的区别的其他问题,但我无法真正解决这个问题。
public class Class1 {
private TestActivity testActivity;
// This line of code is ran when an event is triggered:
// But testActivity seems to be null and I get
// Caused by: java.lang.NullPointerException:
//Attempt to invoke virtual method on this line:
testActivity.getBackData(var);
public void setParam(TestActivity testA){
// Running testA.getBackData(var) here works fine.
// But assigning this.testActivty makes testActivity
//null outside of this method.
this.testActivity = testA;
}
}
活动:
public class TestActivity extends Activity {
protected void onCreate...{
Class1 c = new Class1();
c.setParam(TestActivity.this);
}
public String getDataBack(String str){}
}
谢谢。
答案 0 :(得分:2)
您尝试使用以下方法调用TestActivity方法:
public class Class1 {
private TestActivity testActivity;
// calling the method
testActivity.getBackData(var);
}
这是一个逻辑错误。
您只能像这样在方法内部调用类的特定方法:
public class Class1 {
private TestActivity testActivity;
public void setParam(TestActivity testA){
this.testActivity = testA;
// calling the method
testActivity.getBackData(var);
}
}
您的以下评论:
// This line of code is ran when an event is triggered:
// But testActivity seems to be null and I get
// Caused by: java.lang.NullPointerException:
//Attempt to invoke virtual method on this line:
testActivity.getBackData(var);
不是Java的工作方式。