Why does my Android app crash with a NullPointerException when initializing a variable with findViewById(R.id.******) at the beginning of the class?
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()
.
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);
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
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.