How to add data to an array in Firebase?

I have an array called subscribedTo for my node users. Now I want to add some push ID's to this array whenever a user subscribes.

But push ID are replaced instead of adding.

How can I add a push id to an array?

Scheme

 "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(); } }); } 
+8
android arrays firebase firebase-database
source share
1 answer

When you call updateChildren() with a map, Firebase takes each key and replaces the object in that place with the value from the map.

Firebase's documentation on updateChildren() says this:

For one key path, such as alanisawesome , updateChildren() updates data only at the first child level, and any data transferred outside the first child level is treated as a setValue () operation.

So, in your case, you replace the entire contents of "/" + Constants.FIREBASE_LOCATION_USERS + "/" + mEncodedEmail + "/subscribedTo" .

The solution is to either make the PROG_ID part of the key on the card:

 userMap.put("/" + Constants.FIREBASE_LOCATION_USERS + "/" + mEncodedEmail + "/subscribedTo/"+PROG_ID, true); firebaseRef.updateChildren(userMap, ... 

Or just call setValue() at the bottom of the JSON tree:

 firebaseRef.child("/" + Constants.FIREBASE_LOCATION_USERS + "/" + mEncodedEmail + "/subscribedTo/"+PROG_ID).setValue(true); 

You will notice that in both cases I got rid of your array in favor of the recommended structure for this so-called index :

 "subscribedTo": { "-KFPi5GjCcGrF-oaHnjr": true }, 
+9
source share

All Articles