Java Firebase Firestore 从集合中获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46706433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Firebase Firestore get data from collection
提问by Slaven Petkovic
I want to get data from my Firebase Firestore database. I have a collection called user and every user has collection of some objects of the same type (My Java custom object). I want to fill my ArrayList with these objects when my Activity is created.
我想从我的 Firebase Firestore 数据库中获取数据。我有一个名为 user 的集合,每个用户都有一些相同类型的对象(我的 Java 自定义对象)的集合。我想在创建 Activity 时用这些对象填充我的 ArrayList。
private static ArrayList<Type> mArrayList = new ArrayList<>();;
In onCreate():
在 onCreate() 中:
getListItems();
Log.d(TAG, "onCreate: LIST IN ONCREATE = " + mArrayList);
*// it logs empty list here
Method called to get items to list:
调用方法以获取要列出的项目:
private void getListItems() {
mFirebaseFirestore.collection("some collection").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (documentSnapshots.isEmpty()) {
Log.d(TAG, "onSuccess: LIST EMPTY");
return;
} else {
for (DocumentSnapshot documentSnapshot : documentSnapshots) {
if (documentSnapshot.exists()) {
Log.d(TAG, "onSuccess: DOCUMENT" + documentSnapshot.getId() + " ; " + documentSnapshot.getData());
DocumentReference documentReference1 = FirebaseFirestore.getInstance().document("some path");
documentReference1.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
Type type= documentSnapshot.toObject(Type.class);
Log.d(TAG, "onSuccess: " + type.toString());
mArrayList.add(type);
Log.d(TAG, "onSuccess: " + mArrayList);
/* these logs here display correct data but when
I log it in onCreate() method it's empty*/
}
});
}
}
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Error getting data!!!", Toast.LENGTH_LONG).show();
}
});
}
采纳答案by Sam Stern
The get()
operation returns a Task<>
which means it is an asynchronous operation. Calling getListItems()
only starts the operation, it does not wait for it to complete, that's why you have to add success and failure listeners.
该get()
操作返回 a Task<>
,这意味着它是一个异步操作。调用getListItems()
只会启动操作,不会等待操作完成,这就是您必须添加成功和失败侦听器的原因。
Although there's not much you can do about the async nature of the operation, you can simplify your code as follows:
尽管您对操作的异步性质无能为力,但您可以按如下方式简化代码:
private void getListItems() {
mFirebaseFirestore.collection("some collection").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (documentSnapshots.isEmpty()) {
Log.d(TAG, "onSuccess: LIST EMPTY");
return;
} else {
// Convert the whole Query Snapshot to a list
// of objects directly! No need to fetch each
// document.
List<Type> types = documentSnapshots.toObjects(Type.class);
// Add all to your list
mArrayList.addAll(types);
Log.d(TAG, "onSuccess: " + mArrayList);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Error getting data!!!", Toast.LENGTH_LONG).show();
}
});
}
回答by Gowthaman M
Try this..Working fine.Below function will get Realtime Updates from firebse as well..
试试这个..工作正常。下面的函数也将从 firebse 获取实时更新..
db = FirebaseFirestore.getInstance();
db.collection("dynamic_menu").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e !=null)
{
}
for (DocumentChange documentChange : documentSnapshots.getDocumentChanges())
{
String isAttendance = documentChange.getDocument().getData().get("Attendance").toString();
String isCalender = documentChange.getDocument().getData().get("Calender").toString();
String isEnablelocation = documentChange.getDocument().getData().get("Enable Location").toString();
}
}
});
More reference :https://firebase.google.com/docs/firestore/query-data/listen
更多参考:https: //firebase.google.com/docs/firestore/query-data/listen
If You do not want realtime updates refer Below Document
如果您不想实时更新,请参阅下面的文档
https://firebase.google.com/docs/firestore/query-data/get-data
https://firebase.google.com/docs/firestore/query-data/get-data
回答by live-love
Here is a simplified example:
这是一个简化的示例:
Create a collection "DownloadInfo" in Firebase.
在 Firebase 中创建一个集合“DownloadInfo”。
And add a few documents with these fields inside it:
并在其中添加一些包含这些字段的文档:
file_name (string), id (string), size (number)
文件名(字符串)、id(字符串)、大小(数字)
Create your class:
创建您的课程:
public class DownloadInfo {
public String file_name;
public String id;
public Integer size;
}
Code to get list of objects:
获取对象列表的代码:
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("DownloadInfo")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
if (task.getResult() != null) {
List<DownloadInfo> downloadInfoList = task.getResult().toObjects(DownloadInfo.class);
for (DownloadInfo downloadInfo : downloadInfoList) {
doSomething(downloadInfo.file_name, downloadInfo.id, downloadInfo.size);
}
}
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
回答by Dan
This is the code to get the list. Since this is an async task, it takes time that's why the list size shows empty at first. But including the source for the cache data will enable the previous list(and also its size) to be in memory until next task is performed.
这是获取列表的代码。由于这是一项异步任务,因此需要时间,这就是列表大小最初显示为空的原因。但是包含缓存数据的源将使先前的列表(以及它的大小)在内存中,直到执行下一个任务。
Source source = Source.CACHE;
firebaseFirestore
.collection("collectionname")
.get(source)
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (documentSnapshots.isEmpty()) {
return;
} else {
// Convert the whole Query Snapshot to a list
// of objects directly! No need to fetch each
// document.
List<ModelClass> types = documentSnapshots.toObjects(ModelClass.class);
// Add all to your list
mArrayList.addAll(types);
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});