简体   繁体   English

Android中findViewById()上的NullPointerException

[英]NullPointerException on findViewById() in android

In the following code i get a NullPointerException on lines 9/10 with findViewById(). 在下面的代码中,我在第9/10行使用findViewById()获得了NullPointerException。
In my main class I just instantiated an object from this class, to use .getFrom() 在我的主类中,我刚刚实例化了该类中的一个对象,以使用.getFrom()

public class UserInteraction extends Activity {
EditText etFrom;
int from;
EditText etTill;
int till;

public UserInteraction(){
    etFrom = (EditText)findViewById(R.id.et_from);
    etTill = (EditText)findViewById(R.id.et_till);
}

public int getFrom() {
    String s = etFrom.getText().toString();
    int i = Integer.parseInt(s);
    return i;
}

public int getTill() {
    String s = etTill.getText().toString();
    int i = Integer.parseInt(s);
    return i;
}

Is it that the contentView is set in my main class ..? 是在我的主类中设置contentView吗? What could be the cause ? 可能是什么原因 ?

The setContentView method should be called with appropriate layout before calling findViewById . 调用findViewById 之前,应以适当的布局调用setContentView方法。 It is usually called in onCreate(Bundle savedInstance) method. 通常在onCreate(Bundle savedInstance)方法中调用它。

You have to call it from your Activity's onCreate method, as the resources will not have been made available before that point. 您必须从Activity的onCreate方法调用它,因为在此之前资源将不再可用。

So expanding MByD's answer, in your onCreate method, first call setContentView(), then findViewById(). 因此,为了扩展MByD的答案,请在您的onCreate方法中首先调用setContentView(),然后调用findViewById()。

First , you should call the setContentView(int layout) ,in order to set the Content of your Activity , and then you can get your Views ( findViewById(int id) ) ; 首先,您应该调用setContentView(int layout) ,以设置Activity的Content,然后可以获取Views(findViewById(int id));

So your Activity will be like this : 因此,您的活动将如下所示:

public class UserInteraction extends Activity {
EditText etFrom;
int from;
EditText etTill;
int till;

public void onCreate(Bundle savedInstance{
   super.onCreate(saveInstance);
   this.setContentView(R.layout.main);

   etFrom = (EditText)findViewById(R.id.et_from);
   etTill = (EditText)findViewById(R.id.et_till);
} 

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM