【问题标题】:Firebase Firestore Query help android stuido javaFirebase Firestore Query 帮助 android studio java
【发布时间】:2020-04-19 14:54:45
【问题描述】:

好的,这是我的问题。我创建了一个名为“users”的 firestore 数据库,并向每个人添加了来自身份验证的 UID 和他们可以选择的用户名。我想在文本字段中显示他们的用户名。

所以我做到了:

private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference noteRef;

String currentUid = mAuth.getCurrentUser().getUid();
noteRef = db.collection("users");
Query query = noteRef.whereEqualTo("uid", currentUid);

但现在我一无所知......所以首先我把登录到应用程序的 currentUser UID 放入我的 Firestore 数据库中的“用户”中搜索具有相同 UID 的条目,所以我做了这个查询。问题是我现在如何获取用户名?该查询正在提供我正在寻找的条目,但我现在如何获取用户名?

【问题讨论】:

    标签: android firebase google-cloud-firestore


    【解决方案1】:

    如果用户名作为字段存储在用户文档中,可以通过以下方式获取:

    query.get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData().get("username"));
                    }
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });
    

    有关更多示例,请参阅 executing a query 上的 Firebase 文档。


    请注意,通常使用 UID 作为密钥来存储用户的文档,这样可以更容易地查找它们。

    要像这样存储文档,您可以执行以下操作:

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    FirebaseFirestore.getInstxance()
        .collection("users")
        .document(uid)
        .set(...)
    

    然后你会得到它:

    FirebaseFirestore.getInstxance()
        .collection("users")
        .document(uid)
        .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, "DocumentSnapshot data: " + document.getData());
                    } else {
                        Log.d(TAG, "No such document");
                    }
                } else {
                    Log.d(TAG, "get failed with ", task.getException());
                }
            }
        });
    

    您会注意到,我们现在不再需要之前的循环,因为我们获取的是一个特定的文档,而不是需要查询来为用户查找文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多