Cosmin Argatu
Cosmin Argatu

Reputation: 28

android firebase query sub-object across multiple objects

I am trying to find a session with a specific id (not key) without knowing the user id.

Database Structure

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

Answers (2)

Alex Mamo
Alex Mamo

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

Cosmin Argatu
Cosmin Argatu

Reputation: 28

Issue caused by permission denied from Firebase.

Upvotes: 0

Related Questions