本文介紹了android 中 findViewById() 上的 NullPointerException的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
在下面的代碼中,我在第 9/10 行使用 findViewById() 得到 NullPointerException.
在我的主類中,我只是從這個類中實例化了一個對象,以使用 .getFrom()
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()
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;
}
是不是我的主類中設置了 contentView ..?可能是什么原因?
Is it that the contentView is set in my main class ..? What could be the cause ?
推薦答案
setContentView
方法應該在調用 findViewById
之前以適當的布局調用之前.它通常在 onCreate(Bundle savedInstance)
方法中調用.
The setContentView
method should be called with appropriate layout before calling findViewById
. It is usually called in onCreate(Bundle savedInstance)
method.
這篇關于android 中 findViewById() 上的 NullPointerException的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!