2

Is it possible to write a nested structure into firebase realtime db?

In my case I want to write a user to DB which have a reference to a Socks object which have String properties. In the db I need a child called "SocksCards" with childs with its properties. With this sample code the socksCard object is ignored, the user data is updated.

public void onDataChange(@NonNull DataSnapshot snapshot) {
                    User user = snapshot.getValue(User.class);                    
                    user.addSocksCards(socks);
                    userDb.setValue(user);
                }
public class User {
    public String username, surname, firstName, email, id, gender;
    private SocksCard socksCards;
    public User(){
    }

    public User(String username, String surname, String firstName, String email, String id, String gender){
        this.username = username;
        this.surname = surname;
        this.firstName = firstName;
        this.email = email;
        this.id = id;
        this.gender = gender;
    }

    public void addSocksCards(SocksCard sc){
        this.socksCards = sc;
    }
}
public class SocksCard {
    private String socksID;

    public SocksCard(String socksID){
        this.socksID = socksID;
    }

    public String getSocksID() {
        return socksID;
    }

}

1 Answer 1

1

Firebase only consider public fields, getters and setters when reading/writing Java objects from/to the database. Since SocksCard socksCards is private, and there is no getters and/or setter, the field is indeed ignored.

The two simplest approaches are to either mark the field as public:

public SocksCard socksCards

, or to add a public getter for it:

public SocksCard getSocksCards(){
    return this.socksCards;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh my... what stupid mistake. Thank you! Works perfectly. Btw. is this the way to go to update/append data? I Have not found a better way.
I tend to prefer performing the writes on the deepest level, so would probably do something like FirebaseDatabase.getInstance().ref("users").child(uid).child("socksCards").setValue(socks). But that's a personal preference, nothing that makes it pertinently better that I know of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.