Firebase onDataChange - Value Event Listener not listening for changes

I am trying to read a list of data from a user account which looks like this: db

But the onDataChange listener is not being called.

I would like to get the values of "checked" and "desc"; However, when I add a listenForSingleValueEvent listener like below, onDataChange is not called and I do not retrieve the values.

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("accounts")
            .child(uid).child("user_t").child(item_id);
//"user_t" has been shortened for this post

    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.i(TAG, "onDataChange: Getting single data");

            String name = (String) dataSnapshot.child("checked").getValue();
            String date = (String) dataSnapshot.child("desc").getValue();
        }
    //on Cancel etc..
    };

Even with only:

String name = (String) dataSnapshot.child("checked").getValue();"

Inside onDataChange it still will not fire. From what I've read from the Firebase docs, I must use a listener to read data.

I have similar code in another section of the app which more or less does the same thing as the above code is supposed to and it works perfectly.

I've been having a lot of trouble with Firebase recently so any help appreciated. Cheers!

1 answer

  • answered 2019-01-11 08:31 Alex Mamo

    You cannot get anything because you aren't looping to get the children within the DataSnapshot object. So to solve this, please use the following lines of code:

    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("accounts")
            .child(uid).child("user_t");
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                String name = ds.child("checked").getValue(String.class);
                String date = ds.child("desc").getValue(String.class);
            }
    
        }
    
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
        }
    };
    

    If you it still doesn't fire, please check the logcat to see that databaseError.getMessage() returns.