【问题标题】:How to update a child node that contains a specific value in the database如何更新包含数据库中特定值的子节点
【发布时间】:2017-12-09 17:34:57
【问题描述】:
String userID = selectedCharacter.getUserID();
String charID = selectedCharacter.getCharID();
Character editedCharacter = new Character(userID, charID, name, hitPoints, armorClass, level, experience, gold);

            databaseRef                     
                    .orderByChild("charID")
                    .equalTo(selectedCharacter.getCharID())
                    .addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            // Translate the character to a map of its data
                            Map<String,Object> updates = editedCharacter.toMap();
                            // Update ONLY the node with charID = editedCharacter.getCharID()
                            databaseRef.updateChildren(updates);
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            throw databaseError.toException();
                        }
                    });

所以我正在尝试更新我的 firebase 数据库中的角色统计信息。如您所见:

here

我使用的代码实际上是将更新放在角色的根目录中。我在这里做错了什么?我不确定如何找到带有密钥的节点,因为我没有将密钥存储在任何地方。

【问题讨论】:

    标签: android json firebase firebase-realtime-database


    【解决方案1】:

    当您对 Firebase 数据库执行查询时,可能会有多个结果。所以快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果列表。

    因此,您的代码将需要处理快照是一个列表的事实。在 Android 的情况下,这意味着您循环遍历 snapshot.getChildren()

    databaseRef                     
        .orderByChild("charID")
        .equalTo(selectedCharacter.getCharID())
        .addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot child: dataSnapshot.getChildren()) {
                    // Translate the character to a map of its data
                    Map<String,Object> updates = editedCharacter.toMap();
                    // Update ONLY the node with charID = editedCharacter.getCharID()
                    child.getRef().updateChildren(updates);
                }
            }
    

    【讨论】:

    • 这似乎是解决方案!谢谢!
    【解决方案2】:

    而不是databaseRef.updateChildren(updates);

    你可以试试

    databaseRef.child(dataSnapshot.getKey()).setValue(updates)

    然后看看它是否有效。

    【讨论】:

      猜你喜欢
      • 2017-10-15
      • 2018-06-02
      • 2018-07-12
      • 2017-08-24
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      相关资源
      最近更新 更多