如何从firestore数据库获取文档id

2023-12-06

我正在尝试通过调用检索文档 IDdoc.getId()但我无法从这段代码中调用它

        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 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);
                    }
                }
            }
        });

如果您将 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。我希望这能帮助那里的人。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从firestore数据库获取文档id 的相关文章

随机推荐