gpt4 book ai didi

java - 如何从 Firestore Android 中的集合中获取文档列表

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:43:50 25 4
gpt4 key购买 nike

我的 Firestore 数据库结构:

|
|=>root_collection
|
|=>doc1
|
|=>collection
|
|=>doc2
|
|=>collection
|
|=>doc3
|
|=>collection

现在我想从 root_collection 中获取文档列表。将有一个包含以下数据的列表 {"doc1", "doc2", "doc3"}。我需要它,因为我想制作一个微调器并将这些数据放入微调器中。然后用户将选择一些文档并下载它。

我尝试使用下面的代码:

firestore.collection("root_collection")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG,document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});

但是代码只有在我拥有文档中没有集合的数据结构时才有效。在其他情况下,QueryDocumentSnapshot 中没有任何文档。

谢谢!

最佳答案

要获得包含 root_collection 中所有文档名称的列表,请使用以下代码:

firestore.collection("root_collection").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<String> list = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
list.add(document.getId());
}
Log.d(TAG, list.toString());
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});

您的 logcat 中的结果将是:

[doc1, doc2, doc3]

Remember, this code will work, only if you'll have some properties within those documents, otherwise you'll end ut with an empty list.

关于java - 如何从 Firestore Android 中的集合中获取文档列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50035752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com