NullPointerException on findViewById() in android

2019-01-15 14:23发布

问题:

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 ?

回答1:

The setContentView method should be called with appropriate layout before calling findViewById. It is usually called in onCreate(Bundle savedInstance) method.



回答2:

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



回答3:

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

}