如何获取Firestore中Collection>Document>Collection>Document路径下的字段
Firestore嵌套结构字段获取方案
你当前的代码已经定位到了categories > 分类文档 > quesansforquiz子集合,只需要补全代码疏漏、确保实体类符合要求就能正常读取文档下的字段:
代码修改点
- 新增Firestore异常判断,避免请求出错时触发空指针
- 验证
Ques实体类符合Firestore序列化规则 - 支持直接从文档快照读取字段,无需实体类映射
优化后代码
dataBabe.collection("categories") .document(catId) // 请确保此处catId是正确的分类文档ID .collection("quesansforquiz") .addSnapshotListener(new EventListener<QuerySnapshot>() { @Override public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) { // 优先处理请求异常 if (error != null) { Toast.makeText(getApplication(), "数据读取失败:" + error.getMessage(), Toast.LENGTH_SHORT).show(); return; } if (value != null && !value.isEmpty()) { List<DocumentSnapshot> list = value.getDocuments(); questionslist.clear(); for (DocumentSnapshot d : list) { // 方式1:实体类映射 Ques ud = d.toObject(Ques.class); ud.setOp1(d.getId()); questionslist.add(ud); // 方式2:手动读取字段示例,无需实体类,字段名和Firestore保持一致即可 /* String question = d.getString("question"); String optionA = d.getString("option1"); String optionB = d.getString("option2"); int correctAns = d.getLong("correctAnswer").intValue(); // 手动构造对象添加到列表即可 */ // 如果有更深层的嵌套字段,可用路径读取,比如info对象下的remark字段: // String remark = d.getString("info.remark"); } ptoAdapter.notifyDataSetChanged(); } else { Toast.makeText(getApplication() , "数据库中未找到对应数据", Toast.LENGTH_SHORT).show(); } } });
Ques实体类要求
Firestore的toObject方法要求实体类必须满足以下规则,否则会映射失败:
- 必须有public的无参构造方法
- 类字段名必须和Firestore文档内的字段名完全一致,字段类型匹配
- 所有需要映射的字段要有对应的getter、setter方法
参考实体类示例:
public class Ques { // 字段名和Firestore文档字段完全对应 private String question; private String option1; private String option2; private String option3; private String option4; private int correctAnswer; private String op1; // 必须保留无参构造 public Ques() {} // 以下为对应字段的getter、setter public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getOption1() { return option1; } public void setOption1(String option1) { this.option1 = option1; } public String getOption2() { return option2; } public void setOption2(String option2) { this.option2 = option2; } public String getOption3() { return option3; } public void setOption3(String option3) { this.option3 = option3; } public String getOption4() { return option4; } public void setOption4(String option4) { this.option4 = option4; } public int getCorrectAnswer() { return correctAnswer; } public void setCorrectAnswer(int correctAnswer) { this.correctAnswer = correctAnswer; } public String getOp1() { return op1; } public void setOp1(String op1) { this.op1 = op1; } }
内容的提问来源于stack exchange,提问作者Kumar Harsh
相关产品推荐
相关产品推荐

