【问题标题】:Read Data from Cloud FireStore Android从 Cloud FireStore Android 读取数据
【发布时间】:2018-10-26 08:39:21
【问题描述】:

此脚本是否错误,因为我在 Cloud Firestore 上添加数据时收到的数据是 null。我不使用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();
    }

这是我的火库:

【问题讨论】:

    标签: java android firebase arraylist google-cloud-firestore


    【解决方案1】:

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

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

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

    一个快速解决这个问题的方法是只在onSuccess()方法内使用该结果,或者如果你想在外面使用它,我建议你从这个post查看我的anwser的最后一部分 我在其中解释了如何使用自定义回调来完成。您也可以看看这个 video 以获得更好的理解。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 2020-03-17
      相关资源
      最近更新 更多