2017-05-28 97 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

相關問題