How to add values to Firebase Firestore without overwriting?

前端 未结 5 1736
孤独总比滥情好
孤独总比滥情好 2020-12-16 17:56

I have two Activities, I am adding data to Firestore from these two activities individually. But, whenever I add second activity data to Firestore, it is overwriting the fir

5条回答
  •  我在风中等你
    2020-12-16 18:20

    There are two ways in which you can achieve this. First one would be to use a Map:

    Map map = new HashMap<>();
    map.put("yourProperty", "yourValue");
    firebaseFirestore.collection("Users").document(user_id).update(map);
    

    As you can see, I have used update() method instead of set() method.

    The second approach would be to use an object of your model class like this:

    YourModelClass yourModelClass = new YourModelClass();
    yourModelClass.setProperty("yourValue");
    firebaseFirestore.collection("Users").document(user_id)
        .set(yourModelClass, SetOptions.mergeFields("yourProperty"));
    

    As you can see, I have used the set() method but I have passed as the second argument SetOptions.mergeFields("yourProperty"), which means that we do an update only on a specific field.

提交回复
热议问题