Firebase Firestore get data from collection

后端 未结 6 968
悲&欢浪女
悲&欢浪女 2020-11-29 09:19

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

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 10:07

    Here is a simplified example:

    Create a collection "DownloadInfo" in Firebase.

    And add a few documents with these fields inside it:

    file_name (string), id (string), size (number)

    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() {
                @Override
                public void onComplete(@NonNull Task task) {
                    if (task.isSuccessful()) {
                         if (task.getResult() != null) {
                                List 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());
                    }
                }
            });
    

提交回复
热议问题