Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
Solution 1
You have both a local variable Button buttonLogin and one declared as a field. In your onCreate method you are setting buttonLogin to the local variable and thus, the field is not initialized.
You need to change the code in your onCreate method to
buttonLogin = (Button) findViewById(R.id.sign_in_button);
Or if you want both...
Button buttonLogin = (Button) findViewById(R.id.sign_in_button);
this.buttonLogin = buttonLogin;
Solution 2
But I declare the private Button buttonLogin at the beinging, Is there something wrong?
yes, there is. In onCreate
you declare and initialize
Button buttonLogin = (Button)findViewById(R.id.sign_in_button);
on the method's scope, which has the same name of the class member. The scope rules hide the class member which remains not initialized. To fix it change
Button buttonLogin = (Button)findViewById(R.id.sign_in_button);
to
buttonLogin = (Button)findViewById(R.id.sign_in_button);
Winston Liu
Updated on June 17, 2022Comments
-
Winston Liu almost 2 years
Here are some pieces of codes:
private Button buttonLogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Button buttonLogin = (Button)findViewById(R.id.sign_in_button); buttonLogin.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { new LoginTask().execute( ((EditText)findViewById(R.id.account)).getText().toString(), ((EditText)findViewById(R.id.password)).getText().toString() ); } }); // Set up the login form. enter code here } private class LoginTask extends AsyncTask<String, String, String> { LoginTask() { buttonLogin.setEnabled(false); }
The logcat shows that
Attempt to invoke virtual method 'voidandroid.widget.Button.setEnabled(boolean)' on a null object reference"
But I declare the private Button buttonLogin at the beinging, Is there something wrong?
Please give me a hand, I'll appreciate.