当我试图通过传递""来保护数据时,所有数据(键值对)都从一个孩子中删除了。为了关键和价值

时间:2017-07-10 06:10:14

标签: android firebase firebase-realtime-database

我正在使用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变量中有一些字符串时没有错误。

2 个答案:

答案 0 :(得分:2)

这种情况正在发生,因为您使用setValue()方法而不是updateChildren()方法。 Firebase数据库构造为一对键和值,因此在Map的情况下,它将旧值替换为新值。因此,要解决此问题,请使用DatabaseReference的updateChildren()方法,您的问题将得到解决。

答案 1 :(得分:0)

这样做:

"root-node" : {
    "schoolNames" : {
        "key":"value1",
        "key":"value2", // and more...
        "key":"NEW_VALUE",
                    }
              }

你应该写下这段代码:

schoolNamesDatabaseReference.child("key").setValue("NEW_VALUE");