【问题标题】:hashmap containskey delete all mathcing data on firebasehashmap containskey删除firebase上的所有匹配数据
【发布时间】:2022-01-14 16:51:29
【问题描述】:

我有一个按钮,它是一个计数器,如果“星星”孩子不正确,则加 1,否则 -1。首先按下执行以下 2 个语句。实际上,我必须将我的 UID 保留在 userkey 孩子中,但在第一次按下被删除的同时,我的明星计数正常添加,它必须从那里删除明星孩子,但这会直接删除我的 UID 存在的任何地方。

   final String uid = currentUser.getUid();
            DatabaseReference allfeed = db.getReference("allfeed").child(post_key);
        allfeed.runTransaction(new Transaction.Handler() {
            @NonNull
            @Override
            public Transaction.Result doTransaction(@NonNull MutableData currentData) {
                ExampleItem star = currentData.getValue(ExampleItem.class);
                if (star == null) {
                    return Transaction.success(currentData);
                }

                if (star.stars.containsKey(uid)) {     
                   star.starCount = star.starCount - 1;
                    star.stars.remove(uid);
                } else {
                    // Star the post and add self to stars
                    star.starCount = star.starCount + 1;
                    star.stars.put(uid, true);
                }  
                currentData.setValue(star);
                return Transaction.success(currentData);
            }


            @Override
            public void onComplete(@Nullable DatabaseError error, boolean committed, @Nullable DataSnapshot currentData) {

            }
        });

public class ExampleItem {
    public ExampleItem(){
    }
    String userid,key,reply,time,text,username;
    public int starCount = 0;
    public Map<String, Boolean> stars = new HashMap<String, Boolean>();
    //
   // GETTER AND SETTER 
   //
    public Map<String, Object> toMap() {
        HashMap<String, Object> result = new HashMap<>();
        result.put("keyuser", userid);
          result.put("username", username);
        result.put("text", text);
        result.put("key", key);
     return  result;
    }

}

【问题讨论】:

  • 请编辑您的问题并添加您的ExampleItem 课程的内容。
  • 已编辑并添加感谢

标签: java android firebase firebase-realtime-database google-cloud-platform


【解决方案1】:

当您尝试将 Firebase 实时数据库中的节点映射到 ExampleItem 类型的对象时:

ExampleItem star = currentData.getValue(ExampleItem.class);

这意味着类中的每个字段都将保存节点中存在的相应字段的值。这意味着类中的所有字段都应该在数据库中完全匹配。

由于 Firebase 实时数据库中的每个节点都可以被视为一个地图,因此当您使用 setValue() 方法时:

currentData.setValue(star);

这意味着您覆盖了该特定位置的数据。由于您的 ExampleItem 类没有名为 userKey 的字段,因此将从数据库中删除该字段。因此,(突出显示的读取)删除操作。要解决此问题,您必须将类中的字段更改为:

String userid,key,reply,time,text,username;
              ?

收件人:

String userid,userKey,reply,time,text,username;
                ?

这样userKey字段就不会被删除了。

【讨论】:

  • 现在我的文本子删除也没有发生任何事情。我意识到这与删除星星无关,因为我关闭了 if 语句仍然删除用户 ID 和文本我猜当我得到 exampleitem getvalue 时有问题
  • 您是否尝试将类中的所有字段修改为与数据库中的相同?如果你这样做会发生什么?有用吗?
猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
  • 1970-01-01
  • 2017-06-30
  • 2015-05-11
  • 1970-01-01
相关资源
最近更新 更多