I'm developing an Android app and every time when the user launches this app, it will generate a new register (if not exist) from this user, on update the existing data, and my app will insert more information in the user node.
Every time I update this node, all others information are lost.
My user class
@IgnoreExtraProperties
public class User {
public String userID;
public String userName;
public String userMail;
public boolean active;
public User() {}
public User(String userID, String userName) {
this.userID = userID;
this.userName = userName;
}
public User(String userID, String userName, String userMail, boolean active) {
this.userID = userID;
this.userName = userName;
this.userMail = userMail;
this.active = active;
}
@Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("user_id", userID);
result.put("name", userName);
result.put("email", userMail);
result.put("active", active);
return result;
}
}
And my update code:
public class FireBaseUser {
public static String FB_REFERENCE_USER = "user";
public void updateUser(String userID, String userName, String userMail, boolean userActive) {
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference(FB_REFERENCE_USER);
User user = new User(userID, userName, userMail, userActive);
Map<String, Object> postValues = user.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put(userID, postValues);
myRef.updateChildren(childUpdates);
}
}
When I call myRef.updateChildren(childUpdates);
, all my old data are updated and my new children (that I created during the app) are lost.
The reference with which you are performing the update is for the path FB_REFERENCE_USER
- which appears to be the path which contains the users.
updateChildren
updates only the immediate children, with the values under those being replaced. So the update is replacing the entire child for the user and is leaving the children for the other users untouched. That is the expected behaviour.
You need to perform the update using a ref for that specific user - so that the properties of that user that are not being updated are left untouched.
That is, you need to do something like this:
User user = new User(userID, userName, userMail, userActive);
Map<String, Object> postValues = user.toMap();
myRef.child(userID).updateChildren(postValues);
The behaviour of updateChildren
is described here in the documentation.
if you want to update only some field, try to use
myRef.child(userID).child("which field do you want to update").setValue(ValueVariable);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With