【发布时间】:2018-09-26 08:22:53
【问题描述】:
文档说
QueryDocumentSnapshot 包含作为查询的一部分从 Firestore 数据库中的文档读取的数据。文档保证存在,并且可以使用 getData() 或 get() 方法提取其数据。
QueryDocumentSnapshot 提供与 DocumentSnapshot 相同的 API 界面。由于查询结果只包含现有文档,exists() 方法将始终返回 true,而 getData() 永远不会为 null。
但它没有解释我什么时候应该使用其中一个。我在SnapshotListener 和Collection 上都试过了,都成功了。
protected void onStart() {
super.onStart();
notebookRef.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {
if (e != null) {
Toast.makeText(MainActivity.this, "Error while loading!", Toast.LENGTH_SHORT).show();
Log.d(TAG, e.toString());
return;
}
String allNotes = "";
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
Note note = documentSnapshot.toObject(Note.class);
String title = note.getTitle();
String description = note.getDescription();
allNotes += "\nTitle: " + title + " Description: " + description;
}
textViewData.setText(allNotes);
}
});
}
【问题讨论】:
-
我不明白你的问题。您永远不会决定使用哪一个 - API 会告诉您您将获得哪一个。在您显示的代码中,您的侦听器正在接收一个 QuerySnapshot,它产生多个 QueryDocumentSnapshot 对象。 DocumentSnapshot 从来没有出现在这里——你没有同时使用它们。您有一个名为
documentSnapshot的变量,但这不是一回事。 -
如果我在 for 循环中将
QueryDocumentSnaptshot替换为DocumentSnaptshot,则应用的行为相同。
标签: android firebase google-cloud-firestore