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"
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);
If you are interested, I have also exaplained in one of my tutorials step by step, the entire authentication process using Google and Firebase.