When using the following reference:
mDatabase.child("questions").child("music")
You are telling Firebase Realtime Database to return all elements that exist under the following hierarchy:
Firebase-root -> questions -> music
You will always get no elements because such a path doesn't exist. I say that because between the "questions" node and the "music" property there is a child missing, which that ID. There two approaches that can help you solve this.
In the first one, you keep your actual schema, without making any change and use the following lines of code, to get, for example, all music questions:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference questionsRef = rootRef.child("questions");
Query query = questionsRef.orderByChild("music");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("music").getValue(String.class);
if (music != null) {
Log.d(TAG, name);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
What kind of music do you like?
Which is more important to you, music or TV?
The second approach would be to create a POJO class like this:
class Question {
public String type, name;
}
Using this approach, you need to change the database schema a little bit, as explained below:
Firebase-root
|
--- questions
|
--- 84384238423842
| |
| --- type: "music"
| |
| --- name: "What kind of music do you like?"
|
--- 8rs8842348234
|
--- type: "music"
|
--- name: "Which is more important to you, music or TV?"
In this way, the following code is required:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference questionsRef = rootRef.child("questions");
Query query = questionsRef.orderByChild("type").equalTo("music");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Question question = ds.getValue(Question.class);
Log.d(TAG, question.name);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be the same as above.