编辑:我不知道为什么这被标记为重复。我知道nullpointerexception问题必须是常见的,但在这种情况下,对象被初始化并正确定义。你联系的问题根本解决了我的问题。
我收到错误,我无法理解原因。几天前这堂课正在上班,我确定我没有改变任何事情。它是一个按钮的空指针异常,但是我对所有按钮和其他工作都采用了相同的方式。我在这里缺少什么?
这是错误:
引起:java.lang.NullPointerException:尝试调用虚方法' void android.widget.Button.setOnClickListener(android.view.View $ OnClickListener)'在空对象引用上
以下是代码:
public class Login extends AppCompatActivity implements View.OnClickListener {
Button bLogin;
EditText etUsername, etPassword;
UserLocalStore userLocalStore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bLogin = (Button) findViewById(R.id.bLogin);
bLogin.setOnClickListener(this); //This is the line the exception points to
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.bLogin:
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
User user = new User(username, password);
authenticate(user);
break;
}
}
private void authenticate(User user){
ServerRequests serverRequests = new ServerRequests(this);
serverRequests.fetchUserDataInBackground(user, new GetUserCallback() {
@Override
public void done(User returnedUser) {
if(returnedUser == null){
showErrorMessage();
}else{
logUserIn(returnedUser);
}
}
});
}
private void showErrorMessage(){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Login.this);
dialogBuilder.setMessage("Incorrect user details");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
}
private void logUserIn(User returnedUser){
userLocalStore.storeUserData(returnedUser);
userLocalStore.setUserLoggedIn(true);
}
}
以及XML,以防万一:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:padding="10dp">
<EditText
android:id="@+id/etUsername"
android:hint="Username"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginTop="50dp"
android:layout_marginBottom="10dp" />
<EditText
android:id="@+id/etPassword"
android:hint="Password"
android:inputType="textPassword"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginBottom="10dp" />
<Button
android:id="@+id/bLogin"
android:text="Login"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
感谢任何帮助,谢谢。