Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase to custom Java object

{
  "users": {
    "mchen": {
      "friends": { "brinchen": true },
      "name": "Mary Chen",
      "widgets": { "one": true, "three": true }
    },
    "brinchen": { ... },
    "hmadi": { ... }
  }
}

How to write custom object class for the above example? The guides in Firebase only show simple example.

like image 235
Andrew Lam Avatar asked Jan 07 '23 19:01

Andrew Lam


1 Answers

As usual, you need a Java class that maps each property from the JSON to a field+getter:

static class User {
    String name;
    Map<String, Boolean> friends;
    Map<String, Boolean> widgets;

    public User() { }

    public String getName() { return name; }
    public Map<String, Boolean> getFriends() { return friends; }
    public Map<String, Boolean> getWidgets() { return widgets; }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", friends=" + friends +
                ", widgets=" + widgets +
                '}';
    }
}

I really just follow these instructions from the Firebase guide on reading data on Android:

We'll create a Java class that represents a Blog Post. Like last time, we have to make sure that our field names match the names of the properties in the Firebase database and give the class a default, parameterless constructor.

Then you can load the information like this:

Firebase ref = new Firebase("https://stackoverflow.firebaseio.com/34882779/users");
ref.addListenerForSingleValueEvent(new ValueEventListenerBase() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
            System.out.println(userSnapshot.getKey()+": "+userSnapshot.getValue(User.class));
        }
    }
});

With this output:

brinchen: User{name='Brin Chen', friends={mchen=true, hmadi=true}, widgets={one=true, three=true, two=true}}

hmadi: User{name='Horace Madi', friends={brinchen=true}, widgets={one=true, two=true}}

mchen: User{name='Mary Chen', friends={brinchen=true}, widgets={one=true, three=true}}

like image 187
Frank van Puffelen Avatar answered Jan 22 '23 06:01

Frank van Puffelen