After authenticating the user and updating the FirebaseUser
table, I would need to save other extra data such as age, gender, address etc. I would like to use the R
A common practice in Firebase is to create for your user a helper class
(model class
, POJO class
) and this the corect way to achieve this:
public class User implements Serializable {
private String name;
private int age;
private String gender;
private String address;
private String email;
public User() {}
public User(String name, int age, String gender, String address, String email) {
this.name = name;
this.age = age;
this.gender = gender;
this.address = address;
this.email = email;
}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public int getAge() {return age;}
public void setAge(int age) {this.age = age;}
public String getGender() {return gender;}
public void setGender(String gender) {this.gender = gender;}
public String getAddress() {return address;}
public void setAddress(String address) {this.address = address;}
public String getEmail() {return email;}
public void setEmail(String email) {this.email = email;}
}
Because you need a unique identifier for your users, the uid
is the perfect choice. You can get the uid
using the following line of code:
String uid = FirebaseUser.getInstance().getCurrentUser().getUid();
To insert data into you database, you need to create an object of User class. So please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
User user = new User("John", 25, "male", "101 Main Street", "john@email.com");
usersRef.child(uid).setValue(user);
In this you can simply use the public setters and getters to add/get data from your Firebase database.
Your database will look like something like this:
Firebase-root
|
--- users
|
--- uid1
|
--- name: "John"
|
--- age: 25
|
--- gender: "male"
|
--- address: "101 Main Street"
|
--- email: "john@email.com"
That's correct, to get the current user's unique ID you can use:
FirebaseUser.getInstance().getCurrentUser().getUid();
And you can then store details about a user into the Firebase Realtime Database using that unique ID as a key, something like:
FirebaseUser user = FirebaseUser.getInstance().getCurrentUser();
String userId = user.getUid();
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
HashMap<String, Object> userDetails = new HashMap<>();
message.put("name", "P. Sherman");
message.put("age", 50);
message.put("gender", "male");
message.put("address", "42 Wallaby Way, Sydney");
message.put("email", user.getEmail());
messagesRef.child(userId).setValue(userDetails);