因此,我在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。我不知道我做错了什么。
答案 0 :(得分:2)
您需要在users
中添加集合名称(DocumentReference
)
更改
DocumentReference documentReference = db.document(curUser);
到
DocumentReference documentReference = db.collection("users").document(curUser);