Reputation: 360
I just wanna get boolean data from my firebase database and then count how many boolean data in.
This is my json tree in my database.
"user_study_condition" : {
"1lYNWnabn7a6mj9cPOcayHOGUjx2" : {
"algorithm" : {
"bubble" : true,
"insert" : false,
"name" : "알고리즘"
},
"data_structure" : {
"name" : "자료구조",
"queue" : true,
"stack" : false
}
}
}
I want to count only true data. In this tree, I will count 2 true data. and then add to the List. I already know how to retrieve data from database like 'addSingleValueListener... addValueListener..'
But I don't know how to count boolean data amount.
I have to count boolean data dynamically. because subject will be created dynamically. and boolean data will be changed frequently. So I would like to know the solution considering this.
Thank you for your reply.
Upvotes: 1
Views: 1470
Reputation: 753
You can do this by using equalTo
myRef.orderByChild(childName).equalTo(true);
then on your listener you can get the count by
dataSnapShot.getChildrenCount()
Hope this helps
EDIT:
Try this one for dynamic keys. First is getting your base refrence. Example
myRef = ref.child("1lYNWnabn7a6mj9cPOcayHOGUjx2")
Then add listener to this then inside the listener do 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();
}
}
}
Upvotes: 3
Reputation: 1387
If you're sure the only boolean fields in your object are bubble
, insert
, queue
and stack
you can create a boolean list and add the value of these fields to it. Then you can do the following:
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++;
Kotlin
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 }
Upvotes: 2