Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase for Android, How can I loop through a child (for each child = x do y)

Tags:

This is what my test looks like:

enter image description here

I won't use the fields above, it's just a dummy. But I would like to go through all the children on "users" and for each email return a:

System.out.println(emailString); 

The only way I found of listing an object is using firebaseAdapter, is there another way of doing it?

like image 726
Rosenberg Avatar asked Nov 01 '16 18:11

Rosenberg


People also ask

How do I use firebase persistence?

For Android and Apple platforms, offline persistence is enabled by default. To disable persistence, set the PersistenceEnabled option to false . For the web, offline persistence is disabled by default. To enable persistence, call the enablePersistence method.

How do I find the number of children in firebase?

Show activity on this post. retrieve childs of Day 1 to an array and count the array that ll be the no of child. Show activity on this post. add another lister to days that will give you all matches you played on a day.

What method is used to populate a firebase reference with data?

Use the push() method to append data to a list in multiuser applications. The push() method generates a unique key every time a new child is added to the specified Firebase reference.


2 Answers

The easiest way is with a ValueEventListener.

    FirebaseDatabase.getInstance().getReference().child("users")             .addListenerForSingleValueEvent(new ValueEventListener() {                 @Override                 public void onDataChange(DataSnapshot dataSnapshot) {                     for (DataSnapshot snapshot : dataSnapshot.getChildren()) {                         User user = snapshot.getValue(User.class);                         System.out.println(user.email);                     }                 }                 @Override                 public void onCancelled(DatabaseError databaseError) {                 }             }); 

The User class can be defined like this:

class User {   private String email;   private String userId;   private String username;   // getters and setters... } 
like image 62
rubenlop88 Avatar answered Oct 13 '22 23:10

rubenlop88


FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference(); myRef.addValueEventListener(new ValueEventListener() {  @Override  public void onDataChange(DataSnapshot dataSnapshot) {     for(DataSnapshot item_snapshot:dataSnapshot.getChildren()) {        Log.d("item id ",item_snapshot.child("item_id").getValue().toString());       Log.d("item desc",item_snapshot.child("item_desc").getValue().toString());      }   } } 
like image 37
Amol Dhanwat Avatar answered Oct 13 '22 23:10

Amol Dhanwat