Taken from the Firebase example, if I have a Dinosaurs facts data structure like this:
{
"lambeosaurus": {
"name": "lamby",
"work": "eat",
"dimensions": {
"height" : 2.1,
"length" : 12.5,
"weight": 5000
}
},
"stegosaurus": {
"name": "stego",
"work": "play",
"dimensions": {
"height" : 4,
"length" : 9,
"weight" : 2500
}
}
}
How can I represent this structure in a Android Class for Firebase to cast from DataSnapshot.getValue(DinosaurFacts.class)
?
name, and work are represented as Strings, but how to represent "dimensions" collection in the class?
Also how can I access data values from DataSnapshot
about height & weight?
EDIT I can get the individual elements looping through the snapshot, but am trying to find how to represent the data in the class structure.
for(DataSnapshot child : dataSnapshot.getChildren()) {
Log.d("hz-key:", child.getKey().toString());
Log.d("hz-val:", child.getValue().toString());
}
getKey() returns the key (last part of the path) of the location of the Snapshot. getReference() returns the Reference for the location that generated this Snapshot. getValue() returns the data contained in this Snapshot. hasChild() returns true if the specified child path has (non-null) data.
This is because Firebase does not support Arrays directly, but it creates a list of objects with integers as key names.
getInstance(FirebaseApp app, String url) Gets a FirebaseDatabase instance for the specified URL, using the specified FirebaseApp. DatabaseReference. getReference() Gets a DatabaseReference for the database root node.
A DataSnapshot instance contains data from a Firebase Database location. Any time you read Database data, you receive the data as a DataSnapshot.
The JavaBean class to represent this structure is:
public static class DinosaurFacts {
String name;
String work;
Dimensions dimensions;
public String getName() {
return name;
}
public String getWork() {
return work;
}
public Dimensions getDimensions() {
return dimensions;
}
public class Dimensions {
double height;
long weight;
double length;
public double getHeight() {
return height;
}
public long getWeight() {
return weight;
}
public double getLength() {
return length;
}
}
}
Then you can read a dino with:
DinosaurFacts dino = dinoSnapshot.getValue(DinosaurFacts.class);
And access the dimensions with for example:
dino.getDimensions().getWeight();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With