Symbiose Studios
Symbiose Studios

Reputation: 73

Android Firebase Realtime: Writing an object with nested objects into db

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;
    }

}

Upvotes: 2

Views: 295

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

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;
}

Upvotes: 1

Related Questions