Reputation: 9705
This is my JSON Tree in the Firebase Realtime database. I just want to iterate and read through all of the items under questions
. 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.
public void readfromFireDB() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference().child("questions");
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
**THIS IS THE ERROR, ques comes back as NULL**
Question ques = dataSnapshot.getValue(Question.class);
String key = dataSnapshot.getKey();
}
@Override
public void onCancelled(DatabaseError error) {
}
});
}
This Issue: ques
in onDataChanged()
comes back as a null reference. May be I am not accessing the children under questions
properly?
Upvotes: 0
Views: 440
Reputation: 599216
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();
}
}
Upvotes: 2