[英]How do I add data to the Firebase database?
I cannot add any data on the Firebase Realtime Database.我无法在 Firebase 实时数据库中添加任何数据。 Database connections are ok but I cannot add any data.
数据库连接正常,但我无法添加任何数据。 When I click to button, add to data on my database.
当我单击按钮时,添加到我的数据库中的数据。
MainActivity.java - codes MainActivity.java - 代码
private FirebaseDatabase database;
private DatabaseReference dbRef;
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String plan,note,date,time,remb,eventId;
plan = etplan.getText().toString();
note = etnote.getText().toString();
date = etdate.getText().toString();
time = ettime.getText().toString();
if (remember.isChecked()==true){
remb= "true";
}
else{
remb = "false";
}
database = FirebaseDatabase.getInstance();
dbRef = database.getReference("events");
eventId = dbRef.push().getKey();
event = new Events(plan,note,date,time,remb);
dbRef.child(eventId).setValue(event);
Toast.makeText(MainActivity.this,"Events Added SUCCESSFULLY!", Toast.LENGTH_SHORT).show();
}
});
Events.java - codes Events.java - 代码
public class Events {
String plan;
String note;
String date;
String time;
String remb;
public Events(){
}
public Events(String plan, String note, String date, String time, String remb){
this.plan=plan;
this.note=note;
this.date=date;
this.time=time;
this.remb=remb;
}
}
I am getting the following error in run : at com.cdirect.agenda.MainActivity$4.onClick(MainActivity.java:118)我在运行时收到以下错误:在 com.cdirect.agenda.MainActivity$4.onClick(MainActivity.java:118)
this code:这段代码:
dbRef.child(eventId).setValue(event);
and before this code of eventID (is String)在这个 eventID 代码之前(是字符串)
eventId = dbRef.push().getKey().toString();
What you can do is to add a listener to setValue(event)
method like this:您可以做的是向
setValue(event)
方法添加一个侦听器,如下所示:
dbRef.child(eventId).setValue(event)
.addOnCompleteListener { task ->
if(task.isSuccessful) {
Toast.makeText(this, "Successful", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
}
}
Now task.getException().getMessage()
will let you know what the actual problem is about saving your event data.现在
task.getException().getMessage()
将让您知道保存事件数据的实际问题是什么。
Also, don't forget to check the database rules that read and write is set to true
.另外,不要忘记检查 read 和 write 设置为
true
的数据库规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.