Accessing Firebase Database Objects Below Child
I have a data structure as such: I am calling .addListenerForSingleValueEvent() on my Polls reference, and I have a Pojo class mapped to the poll. However, since I do not know the
Solution 1:
If you don't know anything about the poll to show, the best you can do is show all polls. This can be done by attaching a listener to /Polls
:
DatabaseReferenceref= FirebaseDatabase.getInstance().getReference("Polls");
ref.addListenerForSingleValueEvent(newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot pollSnapshot: dataSnapshot.getChildren()) {
Pollpoll= pollSnapshot.getValue(Poll.class);
Stringkey= pollSnapshot.getKey();
}
}
@OverridepublicvoidonCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
If you want to access a specific poll, you must know something that unique identifies that poll. The simplest of this is knowing its key, in which case you can load it like this:
String key = "-LNlisBxkPbxd00a_QH";
ref.child(key).addListenerForSingleValueEvent(newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
Poll poll = pollSnapshot.getValue(Poll.class);
}
@OverridepublicvoidonCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
If you don't know the key, you need to know a value of a property of the poll to select. For example to get all polls for question y89yuvyu
you can query for that child with:
ref.orderByChild("question").equalToChild("y89yuvyu").addListenerForSingleValueEvent(newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshotpollSnapshot: dataSnapshot.getChildren()) {
Poll poll = pollSnapshot.getValue(Poll.class);
String key = pollSnapshot.getKey();
}
}
@OverridepublicvoidonCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Since there may be multiple polls for that question value, you'll need to loop over the results again as I've done above.
Post a Comment for "Accessing Firebase Database Objects Below Child"