I'm using Firebase for data storage on an Android project, and using the Firebase Java API to deal with data. I'm not sure I'm doing it as efficiently as possible, though, and I'd like some advice on best practices for retrieving and formatting data. My Firebase repository looks something like this....
-POLLS
NUMPOLLS - 5
(pollskey) - NAME - Poll1
NUMELECTIONS - 2
ELECTIONS
(electionskey) - NAME - Election1
NUMNOMINATIONS - 2
NUMVOTERS - 2
NUMBERTOELECT - 1
VOTERS - (votesrkey) - NAME - Charles
NUMBER - (678) 333-4444
.
.
.
(voterskey) - ...
NOMINATIONS - (nominationskey) - NAME - Richard Nixon
NUMBEROFVOTES - 2
.
.
.
(nominationskey) - ...
.
.
.
(electionskey) - ...
.
.
.
(pollskey) - ...
So, for example here I'm trying to get all data out of a poll to list poll name, it's election names, and the candidate names and number of votes for each election. I get the POLLS level DataSnapshot during the OnCreate() function of my main activity like this...
private static final Firebase polls = pollsFirebase.child("Polls");
protected void onCreate(Bundle savedInstanceState) {
polls.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot child : snapshot.getChildren()) {
if (!child.getName().equals("NumPolls")) {
createPollTableAndHeaders(child);
}
}
}
});
}
Then I proceed to read out the individual pieces of data I need by successively calling getValue() on DataSnapshots, and checking the keys of the resulting HashMaps...
private void createPollTableAndHeaders(DataSnapshot poll) {
String pollName = "";
int numPolls;
Object p = poll.getValue();
if (p instanceof HashMap) {
HashMap pollHash = (HashMap) p;
if (pollHash.containsKey("Name")) {
pollName = (String) pollHash.get("Name");
}
if (pollHash.containsKey("Elections")) {
HashMap election = (HashMap) pollHash.get("Elections");
Iterator electionIterator = election.values().iterator();
while (electionIterator.hasNext()) {
Object electionObj = electionIterator.next();
if (electionObj instanceof HashMap) {
HashMap electionHash = (HashMap) electionObj;
if (electionHash.containsKey("Name")) {
String electionName = (String) electionHash.get("Name");
}
}
};
}
}
This seems like a pretty tedious way to drill down through the data structure, and I'm wondering if there's a better way.
I've seen the getValue(java.lang.Class<T> valueType) method in the documentation, but haven't been able to get it to work in my case, since I'm working with composed objects and not just containers for primitive types. How does the function know what Firebase data to assign to which member variables of a model object? Does it match Firebase key names with member variables, and therefore do these have to be exactly the same, with case sensitivity? How would that deal with Firebase generated key names like produced when pushing to a List? How to you construct model objects for composed objects?