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

Firestore集合引用非法致createGroup异常,点击抽屉菜单应用重启

问题解决:Firestore集合引用错误及抽屉刷新问题

核心错误分析

报错java.lang.IllegalArgumentException: Invalid collection reference. Collection references must have an odd number of segments,原因是你拼接的Firestore集合路径格式错误:
原代码中"/users" + userId + "/groups"会生成类似userswEfW4DUgl0gFPv7J8afrTisIiXD3/groups的路径,这里userswEfW4DUgl0gFPv7J8afrTisIiXD3是一个段,groups是第二个段,总共2个偶数段,不符合Firestore的路径规则(集合路径必须是奇数段,格式为集合/文档/集合)。

修复方案

方案1:修正字符串拼接

在users和userId之间添加斜杠,确保路径格式正确:

private void FetchGroup() {
    String userId = mAuth.getCurrentUser().getUid();
    // 修正路径拼接,添加users后的斜杠
    mStore.collection("users/" + userId + "/groups").get().addOnSuccessListener(queryDocumentSnapshots -> {
        groupModelArrayList.clear();
        for (DocumentSnapshot documentSnapshot : queryDocumentSnapshots.getDocuments()) {
            GroupModel groupModel = new GroupModel(documentSnapshot.getString("grupAdi"), documentSnapshot.getString("grupAciklamasi"),
                    documentSnapshot.getString("grupResmi"), (List<String>)documentSnapshot.get("grupNumaralar"), documentSnapshot.getId());
            groupModelArrayList.add(groupModel);
        }
        // 记得添加适配器更新逻辑,比如notifyDataSetChanged()
    }).addOnFailureListener(e -> {
        // 添加错误处理,避免崩溃
        e.printStackTrace();
    });
}

方案2:使用Firestore链式调用(更推荐)

这种方式更直观,不容易出现路径拼接错误:

private void FetchGroup() {
    String userId = mAuth.getCurrentUser().getUid();
    mStore.collection("users")
          .document(userId)
          .collection("groups")
          .get()
          .addOnSuccessListener(queryDocumentSnapshots -> {
              groupModelArrayList.clear();
              for (DocumentSnapshot documentSnapshot : queryDocumentSnapshots.getDocuments()) {
                  GroupModel groupModel = new GroupModel(documentSnapshot.getString("grupAdi"), documentSnapshot.getString("grupAciklamasi"),
                          documentSnapshot.getString("grupResmi"), (List<String>)documentSnapshot.get("grupNumaralar"), documentSnapshot.getId());
                  groupModelArrayList.add(groupModel);
              }
              // 更新适配器
          })
          .addOnFailureListener(e -> e.printStackTrace());
}

抽屉点击刷新问题处理

修复Firestore错误后,若抽屉点击仍导致应用刷新,检查以下几点:

  • 抽屉导航逻辑:是否每次点击都重新创建CreateGroupFragment实例,而非复用已有实例?可以通过Fragment的show/hide方式管理,避免重复初始化。
  • 生命周期回调:确认onCreateView中是否有重复执行的耗时操作,可将FetchGroup移到onResume或使用ViewModel缓存数据,避免每次创建视图都重新请求数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:01:27