Reputation: 921
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();
}
});
}
Upvotes: 11
Views: 12635
Reputation: 598728
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
},
Upvotes: 11