我在使用Firebase。
我的声明、初始化和实施如下:
FirebaseDatabase firebaseDatabase;
DatabaseReference schoolNamesDatabaseReference;
firebaseDatabase = FirebaseDatabase.getInstance();
schoolNamesDatabaseReference = firebaseDatabase.getReference().child("schoolNames");
AutoCompleteTextView schoolNameET = (AutoCompleteTextView) findViewById(R.id.view);
String schoolName = schoolNameET.getText().toString;
//schoolNameEt can be empty.
if (!MainMenuActivity.schoolsList.contains(schoolName)){ // schoolName is a string and can be ""
String schoolNameString = schoolName;
//Removing '.' , '#' , etc. from schoolName
schoolName = schoolName.replace(".","");
schoolName = schoolName.replace("#","");
schoolName = schoolName.replace("$","");
schoolName = schoolName.replace("[","");
schoolName = schoolName.replace("]","");
//Using schoolName as a key (or say child) and schoolNameString as its value.
schoolNamesDatabaseReference.child(schoolName).setValue(schoolNameString);
}我最初的数据库结构如下:
"root-node" : {
"schoolNames" : {
"key1":"value1",
"key2":"value2", // and more...
}
}当我试图将数据保存到Firebase实时数据库时,当AutoCopleteTextView为空(意思是将schoolNames设置为""并调用schoolNamesDatabaseReference.child(schoolName).setValue(schoolNameString);)时,我的数据库结构如下:
"root-node" : {
"schoolNames" : ""
}意味着所有以前的数据都已从"schoolNames"中删除。
为什么会发生这种事?
注意:当
schoolName变量中有一些字符串时,没有错误。
发布于 2017-07-10 12:55:58
之所以发生这种情况,是因为您使用的是setValue()方法,而不是updateChildren()方法。Firebase数据库是以一对键和值的形式构造的,因此在Map的情况下,它将旧的值替换为新的值。因此,要解决这个问题,请使用DatabaseReference的updateChildren()方法,您的问题将得到解决。
发布于 2017-07-10 09:42:24
要做到这一点:
"root-node" : {
"schoolNames" : {
"key":"value1",
"key":"value2", // and more...
"key":"NEW_VALUE",
}
}您应该编写以下代码:
schoolNamesDatabaseReference.child("key").setValue("NEW_VALUE");https://stackoverflow.com/questions/45004833
复制相似问题