【问题标题】:Querying Firestore for uid document after authentification => IllegalStateException身份验证后在 Firestore 中查询 uid 文档 => IllegalStateException
【发布时间】:2018-04-29 05:57:14
【问题描述】:

我在我的 Android 应用中同时使用 Firebase 身份验证和 Firestore。我想做的是以下几点:

  • 用户登录
  • 如果这是用户第一次登录,则会创建由其 uid 命名的文档
  • 如果用户之前已经登录(因此以 uid 命名的文档已经存在),那么我会加载一些进一步的数据。

这是我解决这个问题的逻辑:

  • 从 FirebaseAuth 实例获取 FirebaseUser
  • 从 FirebaseUser 我得到了 uid
  • 使用此 uid 构建 DocumentReference
  • 对 DocumentReference 使用 get() 查询
  • 如果 DocumentSnapshot 为 != null 则用户已存在于 firestore 中
  • 如果 DocumentSnapshot == null 用户不存在,我在 firestore 中创建它

我正在测试下面的代码:

    FirebaseUser user = mAuth.getCurrentUser();
    if(user != null) {
        // get uid from user
        String uid = user.getUid();

        // make a query to firestore db for uid
        DocumentReference userDoc = db.collection("users").document(uid);
        userDoc.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document != null) {
                        Log.d(LOG_TAG, "DocumentSnapshot data: " + task.getResult().getData());
                    } else {
                        Log.d(LOG_TAG, "No such document");
                    }
                } else {
                    Log.d(LOG_TAG, "get failed with ", task.getException());
                }
            }
        });
    }

当 uid 存在于 firestore 中时,我会收到包含适当数据的日志消息,但当它不存在时,我会收到以下异常,并且我找不到使用 DocumentSnapshot.exists() 的方法:

java.lang.IllegalStateException: This document doesn't exist. Use DocumentSnapshot.exists() to check whether the document exists before accessing its fields.

谁能帮我理解我做错了什么?

谢谢一百万! :)

【问题讨论】:

    标签: android firebase google-cloud-firestore


    【解决方案1】:

    get() 返回的对象是DocumentSnapshot,而不是文档本身。 DocumentSnapshot 永远不会为空。使用exists() 方法确定快照是否包含文档。如果exists() 为真,则可以 安全地使用getXXX() 方法之一(在您的情况下,getData() 用于地图)来获取文档的值。

    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot snapshot = task.getResult();
            if (snapshot.exists()) {
                Log.d(LOG_TAG, "DocumentSnapshot data: " + snapshot.getData());
            } else {
                Log.d(LOG_TAG, "No such document");
            }
        } else {
            Log.d(LOG_TAG, "get failed with ", task.getException());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 1970-01-01
      • 2020-11-21
      • 2021-03-19
      • 1970-01-01
      • 2020-11-26
      • 2019-07-17
      • 2021-04-24
      • 2020-06-22
      相关资源
      最近更新 更多