[英]Classes & Activities in Android
Another Java/Android newbie... 另一个Java / Android新手...
My Activity contains a delcaration for a variable of a class that I've defined... public Teams theTeams = null; 我的活动包含我已定义的类的变量的delcaration ... public Teams theTeams = null; Within the onCreate method of this Activity, I create an object of that class... Teams theTeams = new Teams(); 在此Activity的onCreate方法中,我创建了该类的对象...团队theTeams = new Teams(); I've been able to make some changes to this object... theTeams.setName("A", "Jets"); 我已经能够对这个对象进行一些更改...... theTeams.setName(“A”,“Jets”); ... which assigns "Jets" to a string in the class. ...将“喷气机”分配给班级中的字符串。 However, from within a private method of the Activity, attempts to refer to "theTeams" give me a null pointer error. 但是,从Activity的私有方法中,尝试引用“theTeams”会给我一个空指针错误。 I guess there's something about object visibility that I'm not understanding. 我想有一些关于对象可见性的东西,我不理解。 Can someone clarify? 有人可以澄清吗?
You declared first public Teams theTeams = null;
你宣布了第一个public Teams theTeams = null;
Then in the onCreate
method, you have this 然后在onCreate
方法中,你有这个
Teams theTeams = new Teams();
So you are initializing a new theTeams
object of type Team
inside the onCreate
, which you can see only in the scope of onCreate
. 所以你在onCreate
中初始化一个类型为Team
的新的theTeams
对象,你只能在onCreate
的范围内看到它。
So when you call a method on theTeams
in your private method, the method is called in the object you have declared first outside the onCreate
(which is still null) 因此,当您在私有方法中调用theTeams
上的方法时,在onCreate
之外首先声明的对象中调用该方法(该方法仍为null)
So inside, your onCreate
, you have to use: 因此,在内部,您必须使用onCreate
:
theTeams = new Teams();
Something like the following should work (untested): 以下内容应该有效(未经测试):
private Teams theTeams = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
theTeams = new Teams();
}
private void myMethod() {
theTeams.getName();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.