Megool
Megool

Reputation: 999

Extracting Individual Values From Firebase DataSnapshot

I am using addListenerForSingleValueEvent to retrieve data from Firebase database, and I get something like the following:

DataSnapshot { key = Food, value = {-key1=true, -key2=true, -key3=true} }

From this datasnopshot, how can I extract key strings of the food value (i.e. -key, -key2, and -key3) to save in an array individually like array{-key1, -key2, -key3}?

Upvotes: 2

Views: 1354

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

If you already have a snapshot, you can address children with child():

public void onDataChange(DataSnapshot snapshot) {
    System.out.println(snapshot.getKey()); // Food
    System.out.println(snapshot.child("-key1").getValue()); // true
}

You can also loop over the children:

public void onDataChange(DataSnapshot snapshot) {
    for (DataSnapshot child: snapshot.getChildren()) {
        System.out.println(child.getKey()); // "-key1", "-key2", etc
        System.out.println(child.getValue()); // true, true, etc
    }
}

Upvotes: 2

Related Questions