如何从Firestore Android中的集合中获取文档列表 [英] How to get list of documents from a collection in Firestore Android
问题描述
我的Firestore数据库结构:
My structure of Firestore database:
|
|=>root_collection
|
|=>doc1
|
|=>collection
|
|=>doc2
|
|=>collection
|
|=>doc3
|
|=>collection
现在我想从root_collection
获取文档列表.将存在一个包含以下数据{"doc1", "doc2", "doc3"}
的列表.我需要它是因为我想制作一个微调器并将这些数据放入微调器中.然后,用户将选择一些文档并下载.
Now I wanna get list of document from root_collection
. There would be a list with following data {"doc1", "doc2", "doc3"}
. I need it because I want to make a spinner and put these data in the spinner. Then a user would be choose some document and download it.
我尝试使用下面的代码:
I try to use the code below:
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
中没有任何文档.
But the code works only then I have structure of data without collections in the documents. In other case there aren't any documents in QueryDocumentSnapshot
.
谢谢!
推荐答案
要获取包含root_collection
中所有文档名称的列表,请使用以下代码:
To have a list that contains all the name of your documents within the root_collection
, please use the following code:
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中的结果将是:
The result in your logcat will be:
[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.
这篇关于如何从Firestore Android中的集合中获取文档列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!