Zac You
Zac You

Reputation: 25

How to get nested keys in firebase database

database structure

So I have a question is it possible to retrieve the whole child of -Ltlu0PZaSDgydS1akRt under object Student with the condition of (if courseId contains -LuPHOGBwBLTIHn-k4zl) the courseId itself is a nested object within -Ltlu0PZaSDgydS1akRt object.

Any help would be appreciated

Upvotes: 2

Views: 829

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80944

To get the nested keys under courseId try the following:

Query databaseReference = FirebaseDatabase.getInstance().getReference("Student").child("Ltlu0PZaSDgydS1akRt").orderByChild("-Lua7cZD1anNgKuvprjj");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
     if(dataSnapshot.exists()){
       for(DataSnapshot ds : dataSnapshot.getChildren()){
           String key = ds.getKey();
           String value = ds.getValue(String.class);
         } 
    }
} 
    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});

Here you add a reference at node courseId then attach a listener and iterate inside the ids. Then using getKey() you can retrieve the key.

Upvotes: 1

Related Questions