【问题标题】:Firestore - Return a value from a Document Snapshot Java/Android [duplicate]Firestore - 从文档快照 Java/Android 返回一个值 [重复]
【发布时间】:2020-08-20 19:58:28
【问题描述】:

我需要返回从文档快照中检索到的值。我可以在 LOG 中看到正确的值,但由于它超出了范围,并且仅在 onComplete 中,我无法访问它。
你能帮忙吗?

public String getCoEmail() {
    coUserReference = db.collection("users").document(email);
  
    coUserReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
               if (task.isSuccessful()) {
               DocumentSnapshot document = task.getResult();
               if (document.exists()) {
                  String coEmail = document.getString("coEmail");
                  Log.d(TAG, "DocumentSnapshot data: " + document.getString("coEmail"));
                    } else {
                        Log.d(TAG, "No such document");
                    }
                } else {
                    Log.d(TAG, "get failed with ", task.getException());
                }
            }
        });
    return coEmail;
}

【问题讨论】:

    标签: java android google-cloud-firestore


    【解决方案1】:

    Log.d后返回:

    Log.d(TAG, "DocumentSnapshot data: " + document.getString("coEmail"));
    return document.getString("coEmail");
    

    【讨论】:

      【解决方案2】:

      数据是从 Firestore(和大多数云 API)异步加载的,在此过程中您的主代码会继续执行。这意味着您的 return coEmail 现在在 coEmail = document.getString("coEmail") 之前运行,即使您要修复范围问题。

      解决方案是确保所有需要数据的代码都在onComplete 方法中,或者从那里调用。有关此内容的更长示例,请参阅:How to check a certain data already exists in firestore or notFirestore OncompleteListener

      【讨论】:

        猜你喜欢
        • 2021-04-07
        • 1970-01-01
        • 2020-09-26
        • 1970-01-01
        • 1970-01-01
        • 2019-08-02
        • 2022-01-25
        • 2021-09-27
        • 1970-01-01
        相关资源
        最近更新 更多