繁体   English   中英

从Cloud FireStore Android读取数据

[英]Read Data from Cloud FireStore Android

此脚本是否错误,因为在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();
    }

这是我的消防站:

我的消防站

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

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

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

一个快速的解决这个问题是使用该结果只是内部onSuccess()方法,或者如果要在室外使用,我建议你从这个看我anwser的最后部分岗位在我所exaplined它如何使用自定义回调完成。 您也可以观看此视频 ,以更好地理解。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM