【发布时间】:2018-04-07 14:06:03
【问题描述】:
我可以手动查询 Firestore 并获取 ID,但我使用的是 FirestoreRecyclerAdapter,因为它附带了大量开箱即用的额外工作。所以,如果我有这样的代码:
FirebaseFirestore db = FirebaseFirestore.getInstance();
Query query = db.collection(COLLECTION_NAME)
.whereEqualTo("userId", USER_ID)
.limit(LIMIT);
FirestoreRecyclerOptions options = new FirestoreRecyclerOptions
.Builder<SomeEntity>()
.setQuery(query, SomeEntity.class)
.build();
FirestoreRecyclerAdapter adapter = new FirestoreRecyclerAdapter<SomeEntity, MyHolder>(options) {
@Override
public void onBindViewHolder(MyHolder holder, int position, SomeEntity model) {
// I need model ID here
}
}
所以,如果我使用FirestoreRecyclerAdapter,它会自动将我的SomeEntity 类反序列化为model 对象。这一切都很好,但现在我需要将侦听器附加到列表中,并对模型 ID 做出反应。现在,如果我从 Firestore 手动反序列化对象,我会这样做:
for (DocumentSnapshot document : task.getResult()) {
SomeEntity entity = document.toObject(SomeEntity.class).setId(document.getId());
list.add(entity);
}
但是,由于 FirestoreRecyclerAdapter 正在为我进行反序列化,所以我不能自己致电 document.getId()。当我使用onBindViewHolder 方法时,我不再有权访问文档 ID。是否有一些我遗漏的方法,一些从我忽略的适配器中检索 ID 的方法?
注意,我不认为将 ID 作为字段冗余存储是一种解决方案。我宁愿继承和覆盖FirestoreRecyclerAdapter,但如果我能在没有那么多工作的情况下解决这个问题,我更愿意。
【问题讨论】:
-
这有点傻,但我在阅读 this comment. 后将文档 ID 作为字段保存在文档本身中
标签: android firebase google-cloud-firestore firebaseui