NullPointerException on findViewById() in android

前端 未结 3 1614
我在风中等你
我在风中等你 2020-12-06 18:35

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

相关标签:
3条回答
  • 2020-12-06 19:16

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

    }

    0 讨论(0)
  • 2020-12-06 19:27

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

    0 讨论(0)
  • 2020-12-06 19:30

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

    0 讨论(0)
提交回复
热议问题