Firebase Firestore查询帮助android stuido java

问题描述 投票:0回答:1

好,这是我的问题。我创建了一个名为“用户”的存储数据库,并向所有人添加了身份验证中的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个回答
0
投票

如果用户名作为字段存储在用户文档中,则可以使用:]

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());
            }
        }
    });

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

© www.soinside.com 2019 - 2024. All rights reserved.