在身份验证期间,将使用电子邮件和用户名创建用户。现在我正在尝试使用新名称,姓氏,地址等新字段更新该用户的注册时间。但是当我尝试插入一个新字段时,它会更新新字段并删除旧字段。
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;
}
以下方法用于添加和更新firebase数据库。 addUser方法功能正常但在更新方法期间它替换旧数据。
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);
}
答案 0 :(得分:1)
我认为解决方案非常简单,只需在更新前获取旧值,然后使用新字段或新值进行修改,然后执行更新。
要获得oldValues,我不知道使用getValue(User.class)
是否会返回错误,所以为了安全起见,让我们从孩子们那里循环。
private void updateUser() {
mDatabase.child("users").child(userId)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> postValues = new HashMap<String,Object>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
postValues.put(snapshot.getKey(),snapshot.getValue());
}
postValues.put("email", email);
postValues.put("firstName", firstName);
postValues.put("lastName", lastName);
mDatabase.child("users").child(userId).updateChildren(postValues);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
}
);
}
而且,您为new User(String,String,String)
撰写的构造函数是firstName, lastName, and mobileNo
的字段是email
?