0

I'm still trying to learn about this NoSQL database and its integration with Android.

I had a SQL database before and it has some relations between tables, like this

User

int id
text name
int groupId

Group

int id
text name

In Firebase I implement them like this,

{
    "user": {   
        "1": {   
            "name": "Jon",   
            "groups": {   
                "group1": true   
            }   
        }   
    },   
    "groups": {   
       "group1": {   
           "name": "Group 1"   
       }
    }
}

Till here I think its fine, but when I write some code in Java I don't know how to put my POJO. Here is what I've done till now:

public class Group {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class User {

    private String name;
    private Group groups;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Group getGroups() {
        return groups;
    }

    public void setGroups(Group groups) {
        this.groups = groups;
    }
}

And now reading the values. (Is on method OnCreate)

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("user");
myRef.addValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Iterable<DataSnapshot> children = dataSnapshot.getChildren();
        DataSnapshot next = children.iterator().next();
        User value =  next.getValue(User.class);
        Group group = value.getGroups();
    }

    @Override
    public void onCancelled(DatabaseError error) {
             // Failed to read value
    }
});

But my group's value is always null. What am I doing wrong?? How do I relate user with groups?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
user1851366
  • 256
  • 6
  • 20
  • 41

1 Answers1

1

The main problem that I found is your Group object in the User class: In fact, it should not be a custom object at all, if it stays in the current structure, but a Map. This is the map object - a collection which has a key, and a value, just like a child in the Realtime Database.

If a group name (=key) didn't have a true (=value) next to it - the names could have been stored in String variables, but this is not the case, because every child in the Realtime Database must have a value, and storing a "dummy" value next to a group name makes each group a part of a Map. This current "dummy" is a boolean, and that's why this will be the groups' data type:Map<String, Boolean> groups.

Therefore, your User class should be as follows:

public class User {

    private String name;
    private Map<String,Boolean> groups;

A good example of using this exact type would be this one.

Tal Barda
  • 4,067
  • 10
  • 28
  • 53