我的用户节点中有一个名为subscribedTo
的数组。现在我想在订阅用户时向该数组附加一些push ID's
。
但是push ID
正在被替换而不是被追加。
如何将推送ID附加到阵列?
架构
"tester@gmail,com": {
"email": "tester@gmail,com",
"hasLoggedInWithPassword": true,
"name": "tester",
"subscribedTo": [
"-KFPi5GjCcGrF-oaHnjr"
],
"timestampJoined": {
"timestamp": 1459583857967
}
}
CODE
public void onSubscribe(View v) {
final Firebase firebaseRef = new Firebase(Constants.FIREBASE_URL);
final HashMap<String, Object> userMap = new HashMap<String, Object>();
pushIDList.add(PROG_ID);
userMap.put("/" + Constants.FIREBASE_LOCATION_USERS + "/" + mEncodedEmail + "/subscribedTo",
pushIDList);
firebaseRef.updateChildren(userMap, new Firebase.CompletionListener() {
@Override
public void onComplete(FirebaseError firebaseError, Firebase firebase) {
Toast.makeText(ProgramDetail.this, "You are subscribed", Toast.LENGTH_SHORT).show();
}
});
}
答案 0 :(得分:9)
当您使用地图致电updateChildren()
时,Firebase会获取每个密钥,并使用地图中的值替换该位置的对象。
updateChildren()
上的Firebase文档说明了这一点:
给定
alanisawesome
之类的单个关键路径,updateChildren()
仅更新第一个子级别的数据,并且超出第一个子级别传递的任何数据都被视为setValue()操作。 / p>
因此,在您的情况下,您正在替换"/" + Constants.FIREBASE_LOCATION_USERS + "/" + mEncodedEmail + "/subscribedTo"
的全部内容。
解决方案是在地图中创建密钥的PROG_ID
部分:
userMap.put("/" + Constants.FIREBASE_LOCATION_USERS + "/" + mEncodedEmail + "/subscribedTo/"+PROG_ID, true);
firebaseRef.updateChildren(userMap, ...
或者只需在JSON树中较低的位置调用setValue()
:
firebaseRef.child("/" + Constants.FIREBASE_LOCATION_USERS + "/" + mEncodedEmail + "/subscribedTo/"+PROG_ID).setValue(true);
你会注意到,在这两种情况下,我都摆脱了你的阵列,转而支持recommended structure for such a so-called index:
"subscribedTo": {
"-KFPi5GjCcGrF-oaHnjr": true
},