gpt4 book ai didi

java - 写入 Firebase 时出错。应用程序不断崩溃

转载 作者:行者123 更新时间:2023-11-29 18:45:49 25 4
gpt4 key购买 nike

所以,我是 android 和 firebase 的新手。我正在尝试创建一个消息传递应用程序。但是只要我点击发送按钮,我的应用程序就会崩溃。我确切地知道应用程序崩溃的位置。在我尝试将数据放入数据库时​​单击发送按钮后,它立即崩溃了。检查了 Logcat,一切仍然无法弄清楚如何修复它。下面是 MainActivity.java 的代码

导入 com.google.firebase.database.DatabaseReference;导入 com.google.firebase.database.FirebaseDatabase;

公共(public)类 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("");
}
});
}
}

我的消息类代码

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)

最佳答案

尝试像这样初始化您的 DatabaseReference:

DatabaseReference qDatabaseReference = FirebaseDatabase.getInstance().getReference().child("messages");

关于java - 写入 Firebase 时出错。应用程序不断崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52012507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com