0

I have to fetch all children data from firebase real time database? I want to fetch received messages of User2. How to do that? Database example is as given below -

enter image description here

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
sandy
  • 5
  • 5

2 Answers2

1

To be able to fetch the children data, try the following:

 DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users").child("User1").child("MSG_TYPE_SENT");

reference.addListenerForSingleValueEvent(new ValueEventListener() {
 @Override
public void onDataChange(DataSnapshot dataSnapshot) {
  for(DataSnapshot datas: dataSnapshot.getChildren()){
     String msgContent=datas.child("msgContent").getValue().toString();
     String msgType=datas.child("msgType").getValue().toString();
    }
  }
 @Override
public void onCancelled(DatabaseError databaseError) {
    }
 });

This will give you the msgContent and the msgType, to retrieve any data from the database, you need to pass through every node example:-

getReference("users").child("User1").child("MSG_TYPE_SENT");

Then you can loop inside the ids and retrieve the data.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • Can we use map or any other thing to get children instead of using - getReference("users").child("User1").child("MSG_TYPE_SENT"); this?? because if there are number of children this way may be too lengthy. – sandy Sep 26 '18 at 12:41
  • you can add them in one child, `child("User1/MSG_TYPE_SENT")` anyway you should not nest the database alot, it should be flat database – Peter Haddad Sep 26 '18 at 12:45
0

Here you can fetch the User2 Messages Received

        DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("users");

        mDatabase.child("User2").child("MSG_TYPE_RECEIVED").addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                           for(DataSnapshot spanshot : dataSnapshot.getChildren()){

                             String content=snapshot.child("msgContent").getValue(String.class);
                             String type=snapshot.child("msgType").getValue(String.class);

                             //then you can log those values
                             Log.d("Values:",""+content+""+type);

                       }


                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

If the message received change at any time (lets say you want to implement the delete option in realtime of the message like whatsapp) .addValueEventListener will update your UI in realtime if you have coded to show that the message has been deleted

Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77