如何避免覆盖 Firebase 中的数据

How to avoid overwriting of data in firebase

这是我在 Firebase 中添加记录的代码。外面有一个名为 restauCount 的变量,其值 (int) 为 1

public void sendMessage(){

    int restauCount = 1;
    String identifier ="Restaurant" + restauCount;
    Firebase userRef = firebaseRef.child("Caloocan");
    EditText nameInput = (EditText) findViewById(R.id.nameTxt);
    String name = nameInput.getText().toString();

    EditText locInput = (EditText) findViewById(R.id.locationTxt);
    String location = locInput.getText().toString();

    EditText typeInput = (EditText) findViewById(R.id.typeTxt);
    String foodtype = typeInput.getText().toString();
    if (!name.equals("")){
        Map<String, String> caloocan = new HashMap<String, String>();
        caloocan.put("resname", name);
        caloocan.put("resloc", location);
        caloocan.put("foodtype", foodtype);

        Map<String, Map<String, String>> users = new HashMap<String, Map<String, String>>();
        users.put(identifier,caloocan);

        userRef.setValue(users);
        restauCount++;
    }
}

当我再次运行 sendessage() 时。我将在字段中键入内容,当我单击 ADD(即 sendMessage)时,它将添加到 FireBase 中,但是当我添加新数据时。它会覆盖输入的旧数据吗?如何在不覆盖数据的情况下在 Firebase 中添加多个数据? 创建 restauCount 是为了增加我输入的餐厅数量,

使用

userRef.setValue(users).push();

而不是userRef.setValue(users);

您需要更新 identifier 它保持不变 :

int restauCount = 1;
String identifier ="Restaurant" + restauCount;

试试像这样的东西:

    long restauCount = System.currentTimeMillis();
    String identifier ="Restaurant" + restauCount;

每次发送 sendMessage() 时,您的标识符都会得到一个特定的 ID 作为当前时间(以毫秒为单位)+ "Restaurant"

如果保留整数很重要,请告诉我

您一直在使用 相同的参考

String identifier ="Restaurant" + restauCount;
Firebase userRef = firebaseRef.child("Caloocan");
userRef.setValue(users);
restauCount++;

Check the doc:

Using setValue() in this way overwrites data at the specified location, including any child nodes.

在你的情况下,你出于这个原因正在覆盖相同的数据

每次将新子添加到指定的 Firebase 引用时,您应该使用 push() 方法生成唯一 ID。

Firebase userRef = firebaseRef.child("Caloocan");
Firebase newRef =  userRef.push();
newRef.setValue(users);

//to get the key
String key = newRef.getKey();

userRef.push().setValue(users); 每次向指定的 Firebase 引用添加新子项时,push() 方法都会生成一个唯一键