1
votes

How to handle onChildAdded event in firebase android. below is my database json structure

 {
    message{
            "id"=10;
            "name"="xyz"
           }
 }

    public void onChildAdded(DataSnapshot dataSnapshot, String s) {

           // how can I handle the particular child that has added
        }

this method triggers when a new child is added to my reference node. But how can I get the value for the particular child with out typecasting

4

4 Answers

3
votes

The child added is the one returned on the dataSnapshot. So, if you want to get it's key:

String myKey = dataSnapshot.getKey()

For the value:

String myKey = dataSnapshot.getValue(String.class)

For the value you need to define the type you are expecting. On this example I specified that a String is expected, but you can even cast the value to any object you are using (as long as the fields match on your object model and on the dataSnapshot):

User myUser = dataSnapshot.getValue(User.class)

For more details please go to the Firebase official documentation.

1
votes

In reference, add your app firebase console url.

DatabaseReference myFirebaseRef = database.getReference("Your firbase path");
    myFirebaseRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        if(dataSnapshot.hasChild("message")) {
        for (DataSnapshot poly : dataSnapshot.child("message").getChildren()) {
            String id=String.valueOf(poly.child("id").getValue);
            String name=String.valueOf(poly.child("name").getValue);

        }
    }
         }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) 
         {

        }
        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
1
votes

You will need a model class as per the child nodes and entities you have in your database.

public void onChildAdded(DataSnapshot dataSnapshot, String s) {

       ModelClass model = dataSnapshot.getValue(ModelClass.class)
       //assuming this is used for list of data..
       list.add(model);
}

Child Event Listener does not crash even if the child nodes are not available or not yet created dyanamically.You also won't need any loop for moving to the next node.

0
votes

If you want to get just a specific child value then do this

  public void onChildAdded(DataSnapshot dataSnapshot, String s) {
           if(dataSnapshot.hasChild("name")){
              String name = dataSnapshot.child("name").getValue().toString();
           }
        }