RumplyIntegral
RumplyIntegral

Reputation: 85

Can't get value from Firebase Database DataSnapshot

I have read many answers to this question, none solved my problem.

    ValueEventListener dataListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                DataSnapshot ls = ds.child("/leafBox001");
                DataSnapshot cs = ls.child("/currentState");
                Log.i(TAG, "msg " + cs + ls + ds);
            }

Log returns the following:

DataSnapshot { key = leafBox001, value = {lightSensor=6793, currentState=false} }

DataSnapshot { key = currentState, value = null }

DataSnapshot { key = leafBox001, value = null }

As you can see, when I try to access a child the values become null.

I also always get null when using getValue. Example of that code:

    ValueEventListener dataListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                currentState = ds.child("/leafBox001").child("/currentState").getValue(Boolean.class);
                Log.i(TAG, "msg " + cs + ls + ds);
            }

I have tried every variation of the above code, always null.

RTD Structure

enter image description here

Upvotes: 1

Views: 1515

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

Your database structure is like this:

 leafBox001
      lightSensor:6793
      currentState: false

then do the following:

DatabaseReference reference = FirebaseDatabase.getInstance().getReference("leafBox001");

reference.addListenerForSingleValueEvent(new ValueEventListener() {
 @Override
public void onDataChange(DataSnapshot dataSnapshot) {
      String sensor = dataSnapshot.child("lightSensor").getValue().toString();
      String currentState = dataSnapshot.child("currentState").getValue().toString();

}
@Override
public void onCancelled(DatabaseError databaseError) {
    }
});

The snapshot is at the key leafBox001 then you will be able to access the child of that key.

Upvotes: 1

Related Questions