首页 > 解决方案 > 从 Cloud FireStore Android 读取数据

问题描述

此脚本是否错误,因为我收到的数据是null我在 Cloud Firestore 上添加数据时收到的。我不使用RecyclerView,因为我只需要一个数据。

这是脚本:

private void getCustomer(){
        firestoreDB.collection("customer")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            customers = new ArrayList<>();
                            for (DocumentSnapshot doc : task.getResult()) {
                                Customer customer = doc.toObject(Customer.class);
                                customer.setId_customer(doc.getId());
                                customers.add(customer);
                            }
                        } else {
//                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });

        firestoreListener = firestoreDB.collection("customer")
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
                        if (e != null) {
//                            Log.e(TAG, "Listen failed!", e);
                            return;
                        }
                        customers = new ArrayList<>();
                        for (DocumentSnapshot doc : documentSnapshots) {
                            Customer customer = doc.toObject(Customer.class);
                            customer.setId_customer(doc.getId());
                            customers.add(customer);
                        }
                    }
                });

        id_customer = customers.get(0).getId_customer();
    }

这是我的火库:

我的火库

标签: javaandroidfirebasearraylistgoogle-cloud-firestore

解决方案


您现在不能使用尚未加载的东西。换句话说,您不能简单地使用以下代码行:

id_customer = customers.get(0).getId_customer();

在方法之外,onSuccess()因为它总是null由于此方法的异步行为。这意味着当您尝试id_customer在该方法之外使用变量时,数据尚未完成从数据库加载,这就是无法访问的原因。

解决此问题的一个快速方法是仅在onSuccess()方法内部使用该结果,或者如果您想在外部使用它,我建议您从这篇文章中查看我的答案的最后一部分,其中我已经解释了如何使用它来完成自定义回调。您也可以观看此视频以更好地理解。


推荐阅读