Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Firebase - Why Null Values in Map fields are ignored

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"
    }
}
like image 354
keith Avatar asked Nov 22 '25 17:11

keith


1 Answers

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().

like image 94
Frank van Puffelen Avatar answered Nov 25 '25 05:11

Frank van Puffelen