Android+Firebase:如何从数据库获取布尔数据并统计true值数量
统计Firebase数据库中布尔值为True的数量并存入List
嘿,我来帮你搞定这个统计需求!根据你给出的数据库结构,咱们可以通过遍历数据快照的方式,过滤出所有值为true的布尔字段,统计数量后存入List里。下面是具体的实现步骤和代码示例:
核心思路
- 定位到Firebase数据库的
user_study_condition节点 - 监听数据变化(或者用一次性读取的
get()方法,如果你不需要实时更新) - 逐层遍历数据:用户节点 → 学习分类节点(algorithm、data_structure)→ 分类下的字段
- 排除
name字段,只统计值为true的布尔类型数据 - 把最终统计结果存入List中
Kotlin 实现代码
val db = FirebaseDatabase.getInstance().reference.child("user_study_condition") val trueCountList = mutableListOf<Int>() // 用addValueEventListener实现实时监听,如果你只需要一次性读取,换成get().addOnSuccessListener即可 db.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { trueCountList.clear() // 每次数据更新前清空列表,避免重复添加 var totalTrue = 0 // 遍历所有用户节点(如果只需要统计单个用户,直接定位到该节点即可) for (userSnapshot in snapshot.children) { // 遍历用户下的每个学习分类(algorithm、data_structure) for (categorySnapshot in userSnapshot.children) { // 遍历分类下的每个字段 for (itemSnapshot in categorySnapshot.children) { val fieldKey = itemSnapshot.key val fieldValue = itemSnapshot.value // 跳过name字段,只统计布尔值为true的项 if (fieldKey != "name" && fieldValue is Boolean && fieldValue) { totalTrue++ } } } } trueCountList.add(totalTrue) // 这里可以根据需求处理统计结果,比如更新UI或者打印日志 println("统计到的true值数量:$totalTrue") } override fun onCancelled(error: DatabaseError) { // 处理数据库读取失败的情况 println("读取数据出错:${error.message}") } })
Java 实现代码
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("user_study_condition"); List<Integer> trueCountList = new ArrayList<>(); db.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { trueCountList.clear(); int totalTrue = 0; // 遍历所有用户节点 for (DataSnapshot userSnapshot : snapshot.getChildren()) { // 遍历用户下的学习分类 for (DataSnapshot categorySnapshot : userSnapshot.getChildren()) { // 遍历分类下的每个字段 for (DataSnapshot itemSnapshot : categorySnapshot.getChildren()) { String fieldKey = itemSnapshot.getKey(); Object fieldValue = itemSnapshot.getValue(); // 排除name字段,统计布尔值为true的项 if (!"name".equals(fieldKey) && fieldValue instanceof Boolean && (Boolean) fieldValue) { totalTrue++; } } } } trueCountList.add(totalTrue); System.out.println("统计到的true值数量:" + totalTrue); } @Override public void onCancelled(@NonNull DatabaseError error) { System.out.println("读取数据出错:" + error.getMessage()); } });
额外提示
- 如果你只需要统计单个指定用户的true值数量,直接把数据库引用定位到该用户节点即可,比如:
db.child("1lYNWnabn7a6mj9cPOcayHOGUjx2"),这样就可以去掉外层的用户遍历循环 - 如果不需要实时监听数据变化,把
addValueEventListener换成get().addOnSuccessListener来做一次性读取,性能会更优
内容的提问来源于stack exchange,提问作者Junburg
相关产品推荐
相关产品推荐

