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

标签 android null virtual invoke

部分代码如下:

 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 显示 尝试在空对象引用上调用虚拟方法“voidandroid.widget.Button.setEnabled(boolean)””

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

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

最佳答案

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

关于android - 尝试在空对象引用上调用虚拟方法 'void android.widget.Button.setEnabled(boolean)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29435017/

相关文章:

android - 支持图书馆的好处

c# - 林克 "Object reference not set to an instance of an object."

python - Conda:创建虚拟环境

c++ - 不同形状之间的交集

c++ - 子对象中存在 VPTR

android - DragSortListView 无法在 SwipeRefreshLayout 上向下拖动

java - 无法使用 AVD 在 Windows 7 上绑定(bind)端口 1131

android - 带按钮内存的定制适配器

swift - 有人知道 Swift 中 "(nil < 0) == true"和 "(nil <= 0) == true"背后的基本原理吗?

objective-c - 核心数据中没有默认值的可选(数字)属性 - 为什么不鼓励使用它们?