问题
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();
}
}
}
}
});
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);
}
}
}
});
回答1:
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.
回答2:
The following is how to solve it in Javascript, maybe this will help you to convert it to Java.
Using the following method, we can retrieve the document id, dynamically. Notice that we use snapshotChanges(). This is important because once we subscribe to this function, contained in the subscription is the document 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});
});
});
来源:https://stackoverflow.com/questions/57068280/how-to-get-document-id-from-firestore-database