NullPointerException in findViewById () in android

In the following code, I get a NullPointerException on lines 9/10 with findViewById ().
In my main class, I just created 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 that what contentView is installed in my main class ..? What could be the reason?

+7
source share
3 answers

The setContentView method must be called with the appropriate layout before calling findViewById . Usually it is called onCreate(Bundle savedInstance) .

+17
source

You must call it from the Activity onCreate method, since resources will not be available until this point.

So, extending the MByD response, in your onCreate method, first call setContentView (), then findViewById ().

+2
source

First you must call setContentView (int layout) 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); } 

}

+1
source

All Articles