java android 中 findViewById() 上的 NullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6090185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:16:48  来源:igfitidea点击:

NullPointerException on findViewById() in android

javaandroidandroid-activitynullpointerexceptionandroid-edittext

提问by pointour

In the following code i get a NullPointerException on lines 9/10 with findViewById().
In my main class I just instantiated an object from this class, to use .getFrom()

在下面的代码中,我在第 9/10 行使用 findViewById() 得到 NullPointerException。
在我的主类中,我刚刚从这个类中实例化了一个对象,以使用 .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 ..? What could be the cause ?

是不是我的主类中设置了 contentView ..?可能是什么原因 ?

回答by MByD

The setContentViewmethod should be called with appropriate layout beforecalling findViewById. It is usually called in onCreate(Bundle savedInstance)method.

调用之前,setContentView应使用适当的布局调用该方法。它通常在方法中调用。findViewByIdonCreate(Bundle savedInstance)

回答by CL22

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()。

回答by Houcine

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 :

所以你的 Activity 会是这样的:

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);
} 

}

}