【问题标题】:Best practice to store an existing POJO object in a Firebase database将现有 POJO 对象存储在 Firebase 数据库中的最佳实践
【发布时间】:2016-03-31 07:42:51
【问题描述】:

在我的应用程序中,用户登录。首先,我在邮件地址上验证用户。

protected Boolean doAuthenticateWithEmail(final String mEmail, String mPassword)

在回调方法 onAuthenticated 中,用户使用以下 POJO 存储在 Firebase 数据库中:

public class User {

private String emailAddress;
private String profitNumber;
private String userName;

public User() {
    //Default constructor used by Firebase
}

public User(String emailAddress, String profitNumber, String userName) {
    this.emailAddress = emailAddress;
    this.profitNumber = profitNumber;
    this.userName = userName;
}

public String getEmailAddress() {
    return emailAddress;
}

public String getProfitNumber() {
    return profitNumber;
}

public String getUserName() {
    return userName;
}}

这是将用户对象存储在代表邮件地址的节点下的代码。

Firebase userRef = new Firebase(Constants.FIREBASE_URL_USERS);
userRef.setValue(user.getEmailAddress().replace(".",","));
Firebase mailRef = userRef.child(user.getEmailAddress().replace(".",","));
mailRef.setValue(user);

我的问题是: 如果该用户已经存在,最佳实践是什么?我应该先检查数据是否存在还是直接覆盖现有数据。

【问题讨论】:

    标签: java android firebase firebase-realtime-database


    【解决方案1】:

    事实证明,检查是必要的。

         /**
         * Encode user email replacing "." with "," to be able to use it
         * as a Firebase db key
         */
        String mEncodedEmail = mEmail.replace(".", ",");
    
        /* If the user doesn't exists, make a user */
        final Firebase userLocation = new Firebase(Constants.FIREBASE_URL_USERS).child(mEncodedEmail);
        userLocation.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                    /* If nothing is there ...*/
                if (dataSnapshot.getValue() == null) {
    
                    userLocation.setValue(user);
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2011-05-10
      • 1970-01-01
      • 2018-04-26
      • 1970-01-01
      • 2018-08-13
      • 2011-03-23
      • 2011-03-31
      • 2018-07-27
      • 1970-01-01
      相关资源
      最近更新 更多