Reputation: 124
I have this DB:
users: {
0 : {
name: xx
age: 11
books:{
0 : true
3 : true
}
}
1 : {
name: yy
age: 12
books:{
1 : true
4 : true
}
}
}
I have ref to db als:
database = FirebaseDatabase.getInstance();
refdb = database.getReference();
and query als:
Query = refdb.child("users");
i need to get all pairs (name:value) and for users pairs of books (id:true) als:
0 : true
3 : true
I'm using this to get pairs (id:true):
refdb.child("users").child("books").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
pck.setText(pack);
for (DataSnapshot dttSnapshot2 : dataSnapshot.getChildren()) {
pack = dttSnapshot2 .getKey().toString()+":"+dttSnapshot2 .getValue().toString();
pck.append(pack);
}
...
Where pck is a textView. My problem is that everytime he print the empty string in textView. How can I get those data and write them in a textview?
Upvotes: 6
Views: 25050
Reputation: 1766
refdb.child("users").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot uniqueKeySnapshot : dataSnapshot.getChildren()){
//Loop 1 to go through all the child nodes of users
for(DataSnapshot booksSnapshot : uniqueKey.child("Books").getChildren()){
//loop 2 to go through all the child nodes of books node
String bookskey = booksSnapshot.getKey();
String booksValue = booksSnapshot.getValue();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
}
I haven't tested this code as of now, but I hope you get the idea. The unique ID nodes cannot be skipped because firebase does not know which unique id you want to extract data from. So either go through all the unique IDs by using a foreach loop or specify the unique ID from which you want the data.
Upvotes: 15