I discovered when saving a POJO with a map field using Firebase on Android, that if that map contains nulls in the value property of that map, then the whole field is ignored.
The workaround is easy (non-null values will result in the map saving successfully), but I want to understand why is this so?
Model
public class Game {
private String owner;
private Map<String, String> characters;
public Game() {
// empty constructor for Firebase
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Map<String, String> getCharacters() {
return characters;
}
public void setCharacters(Map<String, String> characters) {
this.characters = characters;
}
}
Calling code
final Game game = new Game();
game.setOwner("owner");
game.setCharacters(new HashMap<String, String>());
game.getCharacters().put("Bugs Bunny", null);
game.getCharacters().put("Batman", null);
final Firebase ref = new Firebase("<firebaseurl>/test/" + System.currentTimeMillis());
ref.setValue(game);
Resulting object in Firebase
{
"1456421340781": {
"owner": "owner"
}
}
They're actually not ignored. When you give Firebase a null value for a property/path, you indicate that you want to property or path to be deleted.
From the documentation on Firebase's JavaScript set() method:
Passing null for the new value is equivalent to calling
remove(); all data at this location or any child location will be deleted.
So if you set a value with:
ref.child("keith").setValue(47649);
Then the following will delete it:
ref.child("keith").setValue(null);
This behavior is most useful when you use updateChildren(), but it works equally when you call setValue().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With