I have a question related with how to save the user information with firebase. I extended the user authentication and created a new node on the json tree with users, each user h
There is no way to get the key of the snapshot automatically injected when you call snapshot.getValue(User.class)
.
But you can easily add an extra call that adds the key to the User
object. You'll first need to add a getter and setter for id
to your User
class:
@Exclude
public String getId() { return id; }
@Exclude
public void setId(String id) { this.id = id; }
As you probably already noticed I annotated these with @Exclude
. This tells the database client to ignore the properties when reading from/writing to the database. Without the annotation, you'd also get an id
property in each User's node in the database.
Now you can simply set and get the key when you're reading the property values:
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
user.setId(snapshot.getKey());
System.out.println(user.getId());
}
}
In the above snippet snapshot.getValue(User.class)
gets a user object with all the regular properties, and then user.setId(snapshot.getKey())
adds the key to that object.
When writing back to the database you could also use user.getId()
to determine where to write:
ref.child(user.getId()).setValue(user);