首页 > 解决方案 > Firestore - 从文档快照 Java/Android 返回一个值

问题描述

我需要返回从文档快照中检索到的值。我可以在 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;
}

标签: javaandroidgoogle-cloud-firestore

解决方案


在Log.d之后返回它:

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

推荐阅读