How to update child with new fields in firebase realtime database?

Viewed 11504

During authentication the user is created with email and user name. Now I am trying to update that user with new fields like first name, last name, address, etc on registration time. But when I try to insert a new field it updates with the new fields and the old fields are removed.

public class User {
        String uid,userName,firstName,lastName,email;

        public User() {
        }
       //called on the time of auth 
       public User(String email, String userName) {
            this.email = email;
            this.userName = userName;
        }
        //called on registration process 
        public User( String firstName, String lastName,String mobileNo) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.mobileNo = mobileNo;
        }

        @Exclude
        public Map<String, Object> toMap() {
            HashMap<String, Object> result = new HashMap<>();
            result.put("email", email);
            result.put("userName", userName);
            result.put("firstName", firstName);
            result.put("lastName", lastName);
            return result;
        }

The following methods are used to add and update the firebase database. The addUser method is functional properly but during the update method it replace the old data.

String userId = getUid(); // its retrun firebase current user id as I use 
                          //  auth authentication     
//first time entry in database
private void writeNewUser(String name, String email) {
     User user = new User(name, email);
     Map<String, Object> postValues = user.toMap();
     mDatabase.child("users").child(userId).setValue(postValues);
} 
//Its called during the registration porecess 
private void updateUser() { 
       User user = new User(firstName, lastName, email);
       Map<String, Object> postValues = user.toMap();
       mDatabase.child("users").child(userId).updateChildren(postValues);
}
1 Answers
Related