簡體   English   中英

Android中findViewById()上的NullPointerException

[英]NullPointerException on findViewById() in android

在下面的代碼中,我在第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;
}

是在我的主類中設置contentView嗎? 可能是什么原因 ?

調用findViewById 之前,應以適當的布局調用setContentView方法。 通常在onCreate(Bundle savedInstance)方法中調用它。

您必須從Activity的onCreate方法調用它,因為在此之前資源將不再可用。

因此,為了擴展MByD的答案,請在您的onCreate方法中首先調用setContentView(),然后調用findViewById()。

首先,您應該調用setContentView(int layout) ,以設置Activity的Content,然后可以獲取Views(findViewById(int id));

因此,您的活動將如下所示:

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