Firebase Cloud Firestore引用返回null

时间:2019-07-07 23:45:30

标签: java android firebase google-cloud-firestore

因此,我在Firestore中创建了Firebase用户配置文件,它将保存用户数据,例如其姓名,电子邮件,电话号码和奖励积分。用户使用Google登录名登录。

这就是我将数据写入Firestore的方式。

 private void addNewUser() {
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user != null) {
        String uid = user.getUid();
        for (UserInfo profile : user.getProviderData()) {
            // Id of the provider (ex: google.com)
            String providerId = profile.getProviderId();

            // UID specific to the provider

            // Name, email address, and profile photo Url
            String name = profile.getDisplayName();
            String email = profile.getEmail();


            Map<String, Object> newUser = new HashMap<>();
            newUser.put("Nama", name);
            newUser.put("Email", email);




            // Add a new document with a generated ID
            db.collection("users").document(uid).set(newUser);
                        }


        }


    }

那是可行的。

但是当我尝试使用Document Reference

检索数据时
    @Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user != null) {
        String curUser = user.getUid();
        DocumentReference documentReference = db.document(curUser);
        documentReference.addSnapshotListener(this.getActivity(), new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@javax.annotation.Nullable DocumentSnapshot documentSnapshot, @javax.annotation.Nullable FirebaseFirestoreException e) {
                if (documentSnapshot.exists()) {
                    String userNama = documentSnapshot.getString(KEY_NAMA);
                    String userEmail = documentSnapshot.getString(KEY_EMAIL);

                    namaUser.setText(userNama);
                    emailUser.setText(userEmail);
                }
            }
        });




    } else {

        Intent intent = new Intent(Home.this.getActivity(), LoginActivity.class);
        startActivity(intent);


        }

    }

在这种情况下,文档引用curUser返回null。我不知道我做错了什么。

1 个答案:

答案 0 :(得分:2)

您需要在users中添加集合名称(DocumentReference

更改

DocumentReference documentReference = db.document(curUser);

DocumentReference documentReference = db.collection("users").document(curUser);