我刚刚用四个EditText和一个按钮创建了一个Hello World应用程序。该应用程序崩溃并出现以下错误:我在按钮单击事件上得到了空指针异常。我的代码是:
public class MainActivity extends AppCompatActivity {
FirebaseDatabase mDatabase;
private DatabaseReference mDatabaseReference;
StudentInformation studentInformation;
EditText name, rollNo, course, marks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button saveToDatabase = findViewById(R.id.bottom);
name = findViewById(R.id.nameText);
rollNo = findViewById(R.id.rollNoText);
course = findViewById(R.id.courseNameText);
marks = findViewById(R.id.marksText);
saveToDatabase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
studentInformation = new StudentInformation(name.getText().toString(), rollNo.getText().toString(), course.getText().toString(), marks.getText().toString());
mDatabaseReference = mDatabase.getReference().child("user");
mDatabaseReference.setValue(studentInformation);
}
});
}
}
编辑:如前所述,我使用了错误的ID。使用usign R.id.button而不是R.id.bottom之后,它已得到纠正,但是现在我在行上得到另一个空引用:
mDatabaseReference = mDatabase.getReference().child("user");
作为我的上一期,并且本期也与Null Pointer Exception有关,这就是为什么我没有为此创建新的问题。
任何人都可以提供帮助。我相信,如果Firebase中不存在标签“ user”,Firebase不应自行创建它吗?
确切的错误是:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.FirebaseDatabase.getReference()' on a null object reference
at com.smd.firebasequiz.MainActivity$1.onClick(MainActivity.java:34)
[FirebaseDatabase mDatabase;
在这里mDatabase
等于null,因此您需要在调用类FirebaseDatabase
中的任何方法之前将其初始化:
mDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mDatabase.getReference().child("user");