需要按国家字段筛选时如何从Firestore获取数据,实时数据库代码如何迁移?
问题解决方案
1. 修复空对象引用报错
报错的根本原因是FirebaseFirestore实例db未初始化就被调用,修复方法:
- 先确保模块级
build.gradle已经引入Firestore相关依赖 - 在调用
db.collection()之前,先完成Firestore实例初始化:
// 这行代码必须写在所有db相关调用之前 FirebaseFirestore db = FirebaseFirestore.getInstance();
2. 正确实现按country字段筛选查询
Firestore中条件筛选直接使用whereEqualTo()方法即可实现和原Realtime Database一致的字段匹配效果,完整业务代码如下,完全对齐你原有的逻辑:
FirebaseFirestore db = FirebaseFirestore.getInstance(); // 构造查询:筛选Posts集合下country字段等于指定值的所有文档 db.collection("Posts") .whereEqualTo("country", country) // country替换为你实际要匹配的变量 .get() .addOnSuccessListener(queryDocumentSnapshots -> { progressDialog.dismiss(); postLists.clear(); if (!queryDocumentSnapshots.isEmpty()) { for (DocumentSnapshot document : queryDocumentSnapshots.getDocuments()) { PostModel post = document.toObject(PostModel.class); postLists.add(post); } postAdapter.notifyDataSetChanged(); } else { Toast.makeText(getApplicationContext(), "No data found in Database", Toast.LENGTH_SHORT).show(); } }) .addOnFailureListener(e -> { // 可按需添加查询失败的处理逻辑 progressDialog.dismiss(); Toast.makeText(getApplicationContext(), "查询失败:" + e.getMessage(), Toast.LENGTH_SHORT).show(); });
3. 补充注意事项
PostModel类必须包含public无参构造函数,且类中字段名、类型要和Firestore中存储的字段完全对应,同时为所有字段添加public的getter、setter方法,否则toObject会抛出转换异常- 如果后续需要对查询结果排序,需要在Firestore控制台为对应的字段组合创建索引,执行查询时Logcat会自动输出索引创建的快捷入口
内容的提问来源于stack exchange,提问作者Emily
相关产品推荐
相关产品推荐

