【问题标题】:Android, Firebase How to get only boolean data from database and count themAndroid,Firebase 如何从数据库中仅获取布尔数据并对其进行计数
【发布时间】:2018-04-30 01:16:43
【问题描述】:

我只想从我的 firebase 数据库中获取布尔数据,然后计算其中有多少布尔数据。

这是我数据库中的 json 树。

       "user_study_condition" : {
"1lYNWnabn7a6mj9cPOcayHOGUjx2" : {
  "algorithm" : {
    "bubble" : true,
    "insert" : false,
    "name" : "알고리즘"
  },
  "data_structure" : {
    "name" : "자료구조",
    "queue" : true,
    "stack" : false
  }
}

}

我只想计算真实数据。在这棵树中,我将计算 2 个真实数据。然后添加到列表中。我已经知道如何从数据库中检索数据,例如“addSingleValueListener...addValueListener..”

但我不知道如何计算布尔数据量。

我必须动态计算布尔数据。因为主题将被动态创建。并且布尔数据会经常更改。所以我想知道考虑到这一点的解决方案。

感谢您的回复。

【问题讨论】:

    标签: android firebase firebase-realtime-database


    【解决方案1】:

    您可以通过使用 equalTo 来做到这一点

    myRef.orderByChild(childName).equalTo(true);
    

    然后在你的听众上你可以得到计数

    dataSnapShot.getChildrenCount()
    

    希望对你有帮助

    编辑:

    试试这个动态键。首先是获得你的基础参考。示例

    myRef = ref.child("1lYNWnabn7a6mj9cPOcayHOGUjx2")
    

    然后将侦听器添加到 this 然后在侦听器内部执行此操作

    for (DataSnapshot snapShot: dataSnapshot.getChildren()) {
       Map<String, Object> mp= (Map<String, Object>) snapShot.getValue();
    
       //First is to check if it contains true
       if(mp.containsValue(true)){
         Iterator it = mp.entrySet().iterator();
         while (it.hasNext()) {
            Map.Entry pair = (Map.Entry)it.next();
    
            //If object is a boolean check if it is true
            if(pair.getValue() instanceof Boolean){
               if(pair.getValue()){
                  //This mean that we have 1 true
                  ctrTrue++;
    
                  //This refers to the child reference
                  //For example "1lYNWnabn7a6mj9cPOcayHOGUjx2/algorithm"
                  DatabaseReference itemRef = myRef.child(pair.getKey())
               }
            }
            it.remove();
         }
       }
    }
    

    【讨论】:

    • 我编辑我的问题。拜托,你能再看看我的问题吗?谢谢。
    • 谢谢。这对我帮助很大。
    【解决方案2】:

    如果您确定对象中仅有的布尔字段是bubbleinsertqueuestack,您可以创建一个布尔列表并将这些字段的值添加到其中。然后您可以执行以下操作:

    Java

    List<Boolean> booleanFields = new ArrayList<>();
    booleanFields.add(algorithm.isBubble());
    booleanFields.add(algorithm.isInsert());
    booleanFields.add(dataStructure.isQueue());
    booleanFields.add(dataStructure.isStack());    
    
    int trueCount = 0;
    for (boolean field : booleanFields)
        if (item) trueCount++;
    

    科特林

    val booleanFields = ArrayList<Boolean>()
    booleanFields.add(algorithm.isBubble)
    booleanFields.add(algorithm.isInsert)
    booleanFields.add(dataStructure.isQueue)
    booleanFields.add(dataStructure.isStack)
    
    val count = booleanFields.count { it }
    

    【讨论】:

    • 我编辑我的问题。拜托,你能再看看我的问题吗?谢谢。
    • 您应该创建一个侦听器,将当前的true 计数作为其输入参数,并且在实现它的 UI 中,您将能够动态知道该计数
    • 如果它解决了您的问题,请不要忘记接受这个答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    相关资源
    最近更新 更多