【问题标题】:How can I query for a document name from FireStore?如何从 FireStore 查询文档名称?
【发布时间】:2020-05-26 09:22:46
【问题描述】:

您看,我创建了一个 Google 登录方法,然后在该屏幕上首次登录时应该只显示一个设置,他将输入一些关于他自己的信息,这些信息将被上传到一个文档中到 firestore。该 firestore 文档将具有与 google 登录用户相同的 UID。为了弄清楚用户是否已经有一个提供了一些信息的帐户,我想查询一个文档是否已经存在,并以该特定 uid 作为其文档名。

FirebaseUser user = mAuth.getCurrentUser();
FirebaseFirestore db;

String currentID = mAuth.getCurrentUser().getUid();

// Checken ob User schon Dokument hat
db = FirebaseFirestore.getInstance();
db.collection("users")
         .whereEqualTo("uid", currentID)
         .get()
         .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { // Add the listener callback

@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
    if(task.isSuccessful()) {
        // Check the size of the result to see if any matches were found
        if(task.getResult().size() == 0) {
            // No document exists containing the searched value
        } else {
            // A document already exists containing the searched value
            hasDocument = true;
        }
    } else {
        Log.e(TAG, "There was an error querying the documents.", task.getException());
    }
}
});

if(hasDocument) {
     SendUserToMainActivity();
} else {
     SendUserToSetupActivity();
     Toast.makeText(LoginActivity.this, "You must provide some information first", Toast.LENGTH_LONG).show();
 }

我认为我的问题是我正在查询字段,但我不知道如何查询文档名而不是字段本身。我该怎么做?

这是文档的结构方式:

【问题讨论】:

  • 您不能简单地在onComplete() 方法之外使用hasDocument 的值。 Firebase API 是异步的。因此,请检查重复项,以了解如何使用自定义回调解决此问题。

标签: java android firebase google-cloud-firestore


【解决方案1】:

使用以下代码检查用户是否已经拥有文档

FirebaseUser user = mAuth.getCurrentUser();
FirebaseFirestore db;
String currentID = mAuth.getCurrentUser().getUid();
//Checken ob User schon Dokument hat
db = FirebaseFirestore.getInstance();
db.collection("users")
        .document(currentID)
        .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
                        Log.d(TAG, "Document exists!");
                    } else {
                        Log.d(TAG, "Document does not exist!");
                    }
                } else {
                    Log.d(TAG, "Failed with: ", task.getException());
                }
            }
        });

【讨论】:

  • DocumentSnapshot document = task.getResult();它说这条线需要 Documentsnapshot 但正在接收 Querysnapshot 任何想法?
猜你喜欢
  • 2021-04-22
  • 1970-01-01
  • 2019-04-14
  • 2020-07-08
  • 1970-01-01
  • 2019-04-24
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
相关资源
最近更新 更多