Jonathon
Jonathon

Reputation: 1591

DataSnapshot child returning null

For some reason, the snapshot child "body" is returning NULL, but the title isn't... Really not sure why as title is returning it's value just fine. Using Java.

enter image description here

DatabaseReference mRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mPostsRef = mRef.child("Posts");
String userKey = "-LAKM7c_1Pr7g872svLA"; // Just for testing purposes

mPostsRef.child(userKey).addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            String title = dataSnapshot.child("title").getValue(String.class);
            String body = dataSnapshot.child("body").getValue(String.class);

            Log.d("testing", "Title: " + title + " | Body: " + body);
        }

    });

My Log.d:

Title: test 1 | Body: null

Title: test 2 | Body: null

Upvotes: 2

Views: 2160

Answers (2)

iamkdblue
iamkdblue

Reputation: 3622

try this !

DatabaseReference mRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mPostsRef = mRef.child("Posts");
String userKey = "-LAKM7c_1Pr7g872svLA"; // Just for testing purposes

mPostsRef.child(userKey).addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

       for(DataSnapshot snapshot : dataSnapshot.getChildren())
          {
             Object title = dataSnapshot.child("title").getValue();
             Object body = dataSnapshot.child("body").getValue();

               Log.d("testing", "Title: " + title + " | Body: " + body);
          }


        }

    });

Upvotes: 2

Peter Haddad
Peter Haddad

Reputation: 80914

Change this:

String body = dataSnapshot.child("body").getValue(String.class);

into this:

String body = dataSnapshot.child("body").getValue().toString();

Upvotes: 2

Related Questions