因此,我是android和firebase的新手。我正在尝试创建一个消息传递应用程序。但是,一旦我单击发送按钮,我的应用程序就会崩溃。我确切知道该应用程序崩溃了。单击要在数据库中放置数据的发送按钮后,它立即崩溃。检查了Logcat,一切仍然找不到解决方法。这是MainActivity.java的代码
导入com.google.firebase.database.DatabaseReference; 导入com.google.firebase.database.FirebaseDatabase;
公共类MainActivity扩展了AppCompatActivity {
private Button sendButton;
private TextView editMessage;
private ListView messageList;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference qDatabaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
firebaseDatabase = FirebaseDatabase.getInstance();
qDatabaseReference = qDatabaseReference.getRef().child("messages");
}catch(Exception e){
Toast.makeText(this,"Database Error!", Toast.LENGTH_SHORT);
e.printStackTrace();
}
sendButton = findViewById(R.id.sendButton);
editMessage = findViewById(R.id.messageEdit);
messageList = findViewById(R.id.messageList);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Message message = new Message("user","TEST");
//app crashes here at the line below
qDatabaseReference.push().setValue(message);
editMessage.setText("");
}
});
}
}
我的Message类的代码
public class Message {
private int maxLength = 1000;
private String name;
private String text;
Message(){
name = null;
text = null;
}
Message(String name, String message){
this.name = name;
this.text = message;
}
}
最后在LogCat中发现错误
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.push()' on a null object reference
at com.codeswingstudios.codewise.MainActivity$1.onClick(MainActivity.java:42)
at android.view.View.performClick(View.java:5293)
at android.view.View$PerformClick.run(View.java:21660)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:227)
at android.app.ActivityThread.main(ActivityThread.java:6100)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:859)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
答案 0 :(得分:2)
尝试像这样初始化您的DatabaseReference:
DatabaseReference qDatabaseReference = FirebaseDatabase.getInstance().getReference().child("messages");
答案 1 :(得分:0)
删除引用初始化周围的try和Catch块,您正在尝试获取引用引用。将qDatabaseReference.getReference()
替换为firebaseDatabase.getReference()
firebaseDatabase = FirebaseDatabase.getInstance();
qDatabaseReference = firebaseDatabase.getReference().child("messages");
希望对您有帮助