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

后端 未结 4 1413
萌比男神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 09:54

    Before setting setContentView() you are not able to initialize the view items.Because view will not be exists for activity at that time.

    Keep the initializations in one separate method and call that method after setting the view to the activity.

    0 讨论(0)
  • 2020-11-22 09:59

    Instance member variables are initialized when the instance itself is initialized. It's too early for findViewById()

    Before onCreate() your activity does not yet have a Window that findViewById() needs internally. Before setContentView() (that you should be calling in onCreate()) there are no views to be found either.

    Therefore init your view references in onCreate() and after setContentView().

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 10:15

    Add this code

     EditText username =  findViewById(R.id.editText_Username);
     EditText password = findViewById(R.id.editText_Password);
     TextView inputdata = findViewById(R.id.textView_InputData);
     TextView welcome = findViewById(R.id.textView_Welcome);
     Button login = findViewById(R.id.button_Login);
     Button anotherLogin = findViewById(R.id.button_Login_Another);
    

    in

    onCreate(); 
    

    method after

    setContentView(R.layout.activity_main);
    
    0 讨论(0)
提交回复
热议问题