Reputation: 28
I am trying to find a session with a specific id (not key) without knowing the user id.
Database Structure
I had an initial attempt by looping through all the children of users and creating a new reference every time but it is not working and I can't figure out why nor I know if it should work in the first place.
database.child("users").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snap : dataSnapshot.getChildren()){
database.child("users").child(snap.getKey()).child("sessions")
.orderByChild("id").equalTo(id)
.limitToFirst(1)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot data) {
if (data.exists()) {
Session session = data.getValue(Session.class);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Upvotes: 0
Views: 252
Reputation: 138824
The whole idea of what you are trying to do is correct but you have a single mistake. Your last reference
is wrong. When you are trying to iterate the second time you are missing a child. You need to add .child(sessionId)
. To solve this, please use this code:
database.child("users").child(snap.getKey()).child("sessions").child(sessionId)
.orderByChild("id").equalTo(id)
.limitToFirst(1)
In which sessionId
is the second unique id generated by the push()
method.
Hope it helps.
Upvotes: 1