如何从Firestore数据库获取文档ID [英] How to get document id from firestore database
问题描述
我正在尝试通过调用 doc.getId()
来检索文档ID,但无法从此代码中调用它
I'm trying to retrieve a document id by calling doc.getId()
but I can't call it from this code
db.collection("Pegawai").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
if(e != null) {
Log.d(TAG, e.toString());
}
if (queryDocumentSnapshots != null) {
for (DocumentChange doc: queryDocumentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
Pegawai pegawai = doc.getDocument().toObject(Pegawai.class);
pegawai.setId(doc.getId());
pegawaiList.add(pegawai);
pegawaiListAdapter.notifyDataSetChanged();
}
}
}
}
});
我已经尝试过此代码,并且显然可以用此代码调用 doc.getId()
,但是此代码根本没有填充我的 recyclerview
I've tried this code, and apparently, I can call doc.getId()
with this code, but this code isn't populating my recyclerview
at all
db.collection("Pegawai").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
if(e != null) {
Log.d(TAG, e.toString());
}
if (queryDocumentSnapshots != null) {
for (DocumentSnapshot doc : queryDocumentSnapshots) {
Pegawai pegawai = doc.toObject(Pegawai.class);
pegawai.setId(doc.getId());
pegawaiList.add(pegawai);
}
}
}
});
推荐答案
一个 DocumentChange 对象具有 getDocument(),它返回 DocumentSnapshot 的子类.这意味着它还具有getId()方法.因此,您应该能够使用 doc.getDocument().getId()
来获取正在处理的文档的ID.
A DocumentChange object has a method getDocument() which returns a QueryDocumentSnapshot object. This is a subclass of DocumentSnapshot which means it also has a getId() method. So you should be able to use doc.getDocument().getId()
to get the ID of the document being processed.
这篇关于如何从Firestore数据库获取文档ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!