Firebase 身份验证和数据库 [英] Firebase Auth and Database
问题描述
我对 Firebase 有疑问,我是新手.我想在登录时返回用户名,但该名称在数据库中,我只想返回名称,当然,与身份验证中找到的电子邮件一致,该电子邮件也在数据库中.我的想法是将数据库中的电子邮件与身份验证进行比较,如果是真的,请给我名称.但我不知道如何开发它.解决方案?谢谢
I have a question with Firebase, I'm new to this. I would like to return the user's name when I login, but that name is in Database and I would like to return only the name, of course, coinciding with the email found in the authentication, which is also in the Database. The idea I have is to compare the email from the database with the Auth and if it is true, give me the name. But I would not know how to develop it. Solutions? Thank you
推荐答案
为了实现这一点,您需要使用如下所示的模型类:
In order to achieve this, you need to use a model class that looks like this:
public class UserModel implements Serializable {
private String userEmail;
private String userName;
public UserModel() {}
public UserModel(String userEmail, String userName) {
this.userEmail = userEmail;
this.userName = userName;
}
public String getUserEmail() {return userEmail;}
public String getUserName() {return userName;}
}
要实际添加用户,请使用以下代码:
To actually add a user, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
UserModel userModel = new UserModel("john@email,com", "John");
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
usersRef.child(uid).setValue(userModel);
您的数据库结构将如下所示:
Your database structure will look like this:
Firebase-root
|
--- users
|
--- uid
|
--- userEmail: "john@email,com"
|
--- userName: "John"
此外,要取回userName
,请使用以下代码:
Furthermore, to get back the userName
, please use the following code:
DatabaseReference uidRef = usersRef.child(uid);
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
String userName = dataSnapshot.child("userName").getValue(String.class);
nombre.setText(userName);
Log.d("TAG", userName);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
uidRef.addListenerForSingleValueEvent(eventListener);
如果您有兴趣,我还在我的一个教程中逐步解释了使用 Google 和 Firebase.
If you are interested, I have also exaplained in one of my tutorials step by step, the entire authentication process using Google and Firebase.
这篇关于Firebase 身份验证和数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!