Why Android app crashes for initializing variable with findViewById(R.id.******) at the beginning of the class?

后端 未结 4 1467
萌比男神i
萌比男神i 2020-11-22 09:27

I was just testing input/output, there was no special purpose, this is the last code that had run successfully:

public class MainActivity extends AppCompatA         


        
4条回答
  •  情书的邮戳
    2020-11-22 10:06

    Hey I see that you are defining and initialising the instance variables. What I do is I define the the instance variables - EditText username and then in the onCreate method I initialise them - username = (EditText) findViewById(R.id.editText_Username);

    The reason you don't initialize the instance variables is because the elements are not ready until after the setContentView in onCreate method - I could be wrong with this, but my best practice is define the instance variable and then initialize them in the onCreate method

提交回复
热议问题