2017-05-28 37 views
2

认证期间,用户使用电子邮件和用户名创建。现在我试图用注册时间上的名字,姓氏,地址等新字段来更新该用户。但是,当我尝试插入新字段时,它会使用新字段进行更新,并删除旧字段。如何使用Firebase实时数据库中的新字段更新子项?

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); 
} 
+1

可以显示更新数据库的代码吗? – faruk

+0

@faruk请检查更新 –

回答

1

我认为解决的办法很简单,只要使用旧的价值第一,更新前,并与新的领域或新的值修改,然后做更新。

为了得到旧值,我不知道使用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

相关问题