You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android环境下计算Firebase Firestore数据库集合字段总值

问题分析与修复方案

你的代码存在几个关键问题,导致无法正确计算集合字段总和:

  1. 引用类型错误:最后调用的.document()(无参数)会创建一个新的空文档引用,而非指向整个report集合,需改用CollectionReference指向目标集合。
  2. 监听器类型不匹配:DocumentReference.get()返回Task<DocumentSnapshot>,但你使用了适配集合查询的OnCompleteListener<QuerySnapshot>,类型不兼容。
  3. 未处理空值:getDouble("total")可能返回null,直接累加会触发空指针异常。
  4. 缺少错误处理:未覆盖查询失败的场景,无法排查问题原因。

修复后的代码

// 改为CollectionReference,指向目标集合,移除最后的.document()
CollectionReference productsRef = firebaseFirestore
        .collection("report").document(userID)
        .collection("year").document(userID2)
        .collection("month").document(userID3)
        .collection("report");

productsRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            double total = 0;
            for (QueryDocumentSnapshot document : task.getResult()) {
                // 处理可能的null值,避免空指针
                Double itemCost = document.getDouble("total");
                if (itemCost != null) {
                    total += itemCost;
                }
            }
            dtotal.setText(String.valueOf(total));
        } else {
            // 添加错误日志,排查查询失败原因
            Log.e("TAG", "查询失败", task.getException());
        }
    }
});

额外检查项

  • 确认userID、userID2、userID3的取值正确,对应的文档路径真实存在。
  • 验证目标集合内的每个文档都包含total字段,且字段类型为数值型(Double/Integer)。

内容的提问来源于stack exchange,提问作者TECH PATHAK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 05:35:22