尝试在空对象引用上调用虚拟方法 'void android.widget.Button.setEnabled(boolean)'

Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference

以下是部分代码:

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

logcat 表明 Attempt to invoke virtual method 'voidandroid.widget.Button.setEnabled(boolean)' on a null object reference"

但是我声明了 private Button buttonLogin, 有什么问题吗?

请帮帮我,我将不胜感激。

But I declare the private Button buttonLogin at the beinging, Is there something wrong?

是的,有。在 onCreate 中声明并初始化

Button buttonLogin = (Button)findViewById(R.id.sign_in_button);

在方法的作用域上,它与 class 成员同名。作用域规则隐藏了未初始化的 class 成员。要修复它,请更改

Button buttonLogin = (Button)findViewById(R.id.sign_in_button);

 buttonLogin = (Button)findViewById(R.id.sign_in_button);  

您有一个局部变量 Button buttonLogin 和一个声明为字段的变量。在您的 onCreate 方法中,您将 buttonLogin 设置为局部变量,因此该字段未初始化。

您需要将 onCreate 方法中的代码更改为

buttonLogin = (Button) findViewById(R.id.sign_in_button);

或者如果你想要两者...

Button buttonLogin = (Button) findViewById(R.id.sign_in_button);
this.buttonLogin = buttonLogin;