NullPointerException on findViewById() in android
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;
}
Is it that the contentView is set in my main class ..? What could be the cause ?
The setContentView
method should be called with appropriate layout before calling findViewById
. It is usually called in onCreate(Bundle savedInstance)
method.
You have to call it from your Activity's onCreate method, as the resources will not have been made available before that point.
So expanding MByD's answer, in your onCreate method, first call setContentView(), then 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) ) ;
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);
}
}
精彩评论