3

Can I use updateChildren() using a map of arbitrary (Firebase-friendly) objects in the same way I can use setValue()? The following works fine:

public void addReview(FbReview review, AddCallback callback) {
    Firebase root = mDataRoot.child(REVIEWS_ROOT).child(review.getReviewId());
    root.setValue(review, newAddListener(review, callback));
}

where FbReview is a simple data holder class with an empty constructor and with getters for automatic data structuring (using objects in setValue() is shown in the Firebase documentation for setValue()

However if I try the equivalent updateChildren() follow-on example from the webpage:

@Override
public void addReview(FbReview review, AddCallback callback) {
    Map<String, Object> updates = new HashMap<>();
    updates.put(REVIEWS_ROOT + "/" + review.getReviewId(), review);
    mDataRoot.updateChildren(updates, newAddListener(review, callback));
}

I get an error that suggests the FbReview object I've defined cannot be parsed:

FirebaseException: Failed to parse node with class ... FbReview

If I try the above updateChildren() code but pass a String (review.getSubject() say) rather than an object it works fine suggesting that object parsing doesn't work with updateChildren().

Is this correct?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
chdryra
  • 523
  • 5
  • 17

1 Answers1

5

The updateChildren() method currently does not accept arbitrary Java objects. It only accepts primitive types or Maps of primitive types.

Luckily you can easily convert your Java object to the corresponding map with a Jackson ObjectMapper:

Map<String, Object> userMap = new ObjectMapper().convertValue(user, Map.class);

Then you can put the map of values into the values that you're passing into updateChildren():

Map<String, Object> updatedReview = new HashMap<String, Object>();

updates.put(REVIEWS_ROOT + "/" + review.getReviewId(), updatedReview);
mDataRoot.updateChildren(updates, newAddListener(review, callback));

See this answer too: Android Firebase 2.4 IllegalStateException using new ref.updateChildren()

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Great thanks for the fast response! Incidentally why not overload updateChildren() to accept objects and put theObjectMapper as the first line? – chdryra Apr 10 '16 at 15:24
  • Do you have an updated recommendation on what mapper to use for Firebase 9.x from Google? I believe they no longer use Jackson – Jeremy Sep 28 '16 at 20:54
  • As of SD version 9.6 you can pass a POJO to `updateChildren()`. But you can also still use Jackson yourself if you want. See http://stackoverflow.com/questions/37547399/how-to-deserialise-a-subclass-in-firebase-using-getvaluesubclass-class/37548330#37548330 – Frank van Puffelen Sep 29 '16 at 15:01