问题
I'm using Firebase for Android and faced some misbehaviour of limitToLast() query. What I'm trying to do, is to get the last child of list, and iterate through other children of this node:
database.getReference().child("draws").limitToLast(1).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snap: dataSnapshot.getChildren()){
//Some work
snap.getValue()
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
//Some error handling
}
});
Let's assume, I'm using limitToLast(1) in order to get the child draws/2(refer to the database snap below), which is the last in a draws list. And after, I'm using dataSnapshot.getChildren() to get the list of children of draws/2 node. What I should get after iterating through the dataSnapshot.getChildren() list: "85", "86", "60", "7" as separate values with snap.getValue().toString() in the loop.
What I actually get, is the value of last child without accessing to its children. Result: "[85, 86, 60, 7]". It looks like dataSnapshot.getChildren() doesn't get children of node draws/2, but just gets a whole value of the node.
As a test, I tried to get rid of limitToLast(1) query and substitute with child("2") and everything worked fine.
It is possible that I misunderstood the functionality of limitToLast(), however, if it is true, how can I access children of last node?
回答1:
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
So your code will need to first find the draws/2 child (by looping) and then loop over the children:
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snap: dataSnapshot.getChildren()){
System.out.println(snap.getKey()); // prints 2
for (DataSnapshot snap2: snap.getChildren()){
//Some work
snap.getValue()
}
}
}
It's typically easier to handle query results by using addChildEventListener, because then you'll get a separate call to onChildAdded for each child (and can thus skip the extra loop).
Btw: there are a lot of reasons why the documentation for the Firebase Database doesn't use arrays and even recommends against using arrays. Ignore them at your own peril.
来源:https://stackoverflow.com/questions/41955706/android-firebase-weird-limittolast1-behaviour