更新时间:2022-11-18 22:26:52
使用地图调用 updateChildren()
,Firebase获取每个键,并用该地图中的值替换该位置的对象。
关于 updateChildren()
的Firebase文档对此进行了说明:
给定一个像
alanisawesome
这样的单个键路径,updateChildren()
只会更新第一个子级别的数据,在第一个子级别之外传入的是一个setValue()操作。
所以在你的情况下, /+ Constants.FIREBASE_LOCATION_USERS +/+ mEncodedEmail +/ subscribedTo
的内容。
解决方法是在地图中使
userMap.put(/+ Constants.FIREBASE_LOCATION_USERS +/+ mEncodedEmail +/ subscribedTo /+ PROG_ID,true);
firebaseRef.updateChildren(userMap,...
或者简单地调用
firebaseRef.child( /+ Constants.FIREBASE_LOCATION_USERS +/+ mEncodedEmail +/subscribedTo/\"+PROG_ID).setValue(true);
subscribedTo:{
-KFPi5GjCcGrF-oaHnjr:true
},
I have a array called subscribedTo
in my users node. Now I want to append some push ID's
to that array whenever a user is subscribed.
But the push ID
are being replaced instead of getting appended.
How can i append the push ID's to the array?
Schema
"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();
}
});
}
When you call updateChildren()
with a map, Firebase takes each key and replaces the object at that location with the value from the map.
The Firebase documentation on updateChildren()
says this about it:
Given a single key path like
alanisawesome
,updateChildren()
only updates data at the first child level, and any data passed in beyond the first child level is a treated as a setValue() operation.
So in your case, you are replacing the entire contents of "/" + Constants.FIREBASE_LOCATION_USERS + "/" + mEncodedEmail + "/subscribedTo"
.
The solution is to either make the PROG_ID
part of the key in the map:
userMap.put("/" + Constants.FIREBASE_LOCATION_USERS + "/" + mEncodedEmail + "/subscribedTo/"+PROG_ID, true);
firebaseRef.updateChildren(userMap, ...
Or to simply call setValue()
at the lower location in the JSON tree:
firebaseRef.child("/" + Constants.FIREBASE_LOCATION_USERS + "/" + mEncodedEmail + "/subscribedTo/"+PROG_ID).setValue(true);
You'll note that in both cases I got rid of your array in favor of the recommended structure for such a so-called index:
"subscribedTo": {
"-KFPi5GjCcGrF-oaHnjr": true
},