Firebase Firestore从集合中获取数据

Sla*_*vic 7 java android arraylist google-cloud-firestore

我想从Firebase Firestore数据库中获取数据.我有一个名为user的集合,每个用户都有一些相同类型的对象(My Java自定义对象)的集合.我想在创建Activity时用这些对象填充我的ArrayList.

private static ArrayList<Type> mArrayList = new ArrayList<>();;
Run Code Online (Sandbox Code Playgroud)

在onCreate()中:

getListItems();
Log.d(TAG, "onCreate: LIST IN ONCREATE = " + mArrayList);
*// it logs empty list here
Run Code Online (Sandbox Code Playgroud)

调用获取项目列表的方法:

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();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

Sam*_*ern 12

get()操作返回a Task<>表示它是异步操作.调用getListItems()只会启动操作,它不会等待它完成,这就是为什么你必须添加成功和失败的监听器.

虽然您可以对操作的异步性质做很多事情,但您可以按如下方式简化代码:

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();
                }
            });
}
Run Code Online (Sandbox Code Playgroud)

  • 我处于类似的情况,除了在代码之后,我想获取 ArrayList 的大小。问题是,如果我检查 onSuccess() 内部的大小,它会给出正确的值,但我无法从那里返回,因为它位于侦听器中。但是如果我在该方法中的所有代码之后进行检查,它会返回 0,因为此时异步任务尚未完成。 (2认同)

Gow*_*n M 5

试试这个..工作正常。下面的函数也将从 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();

                   }
                }
        });
Run Code Online (Sandbox Code Playgroud)

更多参考: https: //firebase.google.com/docs/firestore/query-data/listen

如果您不想要实时更新,请参阅下面的文档

https://firebase.google.com/docs/firestore/query-data/get-data