【问题标题】:Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference尝试在空对象引用上调用虚拟方法“void android.widget.Button.setEnabled(boolean)”
【发布时间】:2015-04-03 15:23:34
【问题描述】:

这里有一些代码:

 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, 有什么问题吗?

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

【问题讨论】:

    标签: android null virtual invoke


    【解决方案1】:

    您有一个局部变量 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;
    

    【讨论】:

      【解决方案2】:

      但是我在存在时声明了私有按钮 buttonLogin,有吗 有什么问题吗?

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

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-24
        • 2017-06-02
        • 1970-01-01
        相关资源
        最近更新 更多