0

I have a database that looks like this:

database
   |
  places
     |
     user1
     |  |___indoors: "yes"
     |  |___outdoors: "yes"
     |
     user2
        |___indoors: "yes"   
        |___outdoors: "no"

When I do the following, I get all users places information as a single object (converted to String) with no problems:

ValueEventListener placesListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String locations = dataSnapshot.toString(); // I get the entire tree as String
    }
}

//this is how I set the listener to changes
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference reference = database.child("places");
reference.addValueEventListener(placesListener);

But, when I want only the indoors children, I get DataSnapshot {key = indoors, value = null}.

This is how I try to get only the indoors keys and values (almost the same, only adding extra .child("indoors"):

ValueEventListener placesListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String indoors = dataSnapshot.child("indoors").toString(); // I get value = null
    }
}

// listener remains the same
Grimthorr
  • 6,856
  • 5
  • 41
  • 53
pileup
  • 1
  • 2
  • 18
  • 45

1 Answers1

3

The data contained in a DataSnapshot is relative, like a JSON tree. From the documentation on DataSnapshot#child():

Get a DataSnapshot for the location at the specified relative path. The relative path can either be a simple child key (e.g. 'fred') or a deeper slash-separated path (e.g. 'fred/name/first'). If the child location has no data, an empty DataSnapshot is returned.

In your example, there is no child named indoors directly under the places node. Instead, you have 2 children named user1 and user2 which each have a child named indoors. Therefore, in order to access one of the indoors children, you'll need to do something like:

dataSnapshot.child("user1").child("indoors").toString();

Alternatively, you can iterate through the children using:

for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
    Log.d(childSnapshot.getKey() + ": indoors=" + childSnapshot.child("indoors").toString());
}
Grimthorr
  • 6,856
  • 5
  • 41
  • 53
  • Thank you. By the way, is there a way to retrieve data from the Firebase database NOT in real time? I just want a specific value but get it now, and not in real time – pileup Nov 15 '18 at 09:56
  • Glad to help. Do you mean synchronously? Not exactly, as this isn't a supported feature of Firebase, but there are options, see [Is it possible to synchronously load data from Firebase?](https://stackoverflow.com/q/31700830) for more details. – Grimthorr Nov 15 '18 at 09:59