user1406716 user1406716 - 1 year ago 92
Android Question

Simple read of child nodes from Firebase DB not working

This is my JSON Tree in the Firebase Realtime database. I just want to iterate and read through all of the items under

. I think I am doing something silly wrong.

Under the "My App" - I have a "questions" branch and saving a bunch of data under it. Below is the tree and my code. In the code I point out the part that is crashing. Circled in red below are what I am trying to read.

enter image description here

public void readfromFireDB() {

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference().child("questions");

// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {

**THIS IS THE ERROR, ques comes back as NULL**
Question ques = dataSnapshot.getValue(Question.class);

String key = dataSnapshot.getKey();


public void onCancelled(DatabaseError error) {


This Issue:
comes back as a null reference. May be I am not accessing the children under

Answer Source

By using a ValueEventListener you're accessing the list of questions, not an individual question.

To access each individual question, you'll need to loop over the snapshot:

public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot questionSnapshot: dataSnapshot.getChildren()) {
        Question ques = questionSnapshot.getValue(Question.class);
        String key = questionSnapshot.getKey();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download