[英]How to get document id from firestore database
我正在嘗試通過調用doc.getId()
來檢索文檔 ID,但我無法從這段代碼中調用它
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
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()方法,它返回一個QueryDocumentSnapshot對象。 這是DocumentSnapshot的子類,這意味着它還有一個getId()方法。 因此,您應該能夠使用doc.getDocument().getId()
來獲取正在處理的文檔的 ID。
如果您將 FirestoreRecyclerAdapter 與 Recyclerview 一起使用,請執行此操作。
DocumentSnapshot snapshot = options.getSnapshots().getSnapshot(position);
String dbKey = snapshot.getId();
Log.d(TAG, "The database Key is : "+ dbKey);
然后你可以像這樣將它綁定在視圖持有者上
holder.setDocumentId(dbKey);
然后你可以在任何地方檢索它,這取決於你的 getter 和 setter。 我希望這會幫助那里的人。
下面是如何在Javascript中解決它,也許這可以幫助您將其轉換為Java。 使用以下方法,我們可以動態檢索文檔 ID。 請注意,我們使用了snapshotChanges()
。 這很重要,因為一旦我們訂閱了這個函數,訂閱中包含的就是文檔 ID。
saveMyValuesHere: any[] = []
getPegawai() {
return this.db.collection('Pegawai').snapshotChanges();
}
getPegawai().subscribe(serverItems => {
this.saveMyValuesHere = [];
serverItems.forEach(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
this.saveMyValuesHere.push({ id, ...data});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.