0

When i try to get a Object from addChildListerner(DataSnapShot) it works fine and assign to DataSnapshot to object

This working fine:

  myRef = database.getReference("Chat").child(Combine);
    myRef.orderByKey().limitToLast(1).addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            ChatData user = dataSnapshot.getValue(ChatData.class);
            userChild.add(user);

But when i try to get same Object using ValueListerner(snapshot) app crash i have use everything snapshot.getChildern () snapshot.getValue then app crash.

Error With

myRef = database.getReference("Chat").child(Combine);
myRef.orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        ChatData user = dataSnapshot.getValue(ChatData.class);
                        userChild.add(user);

                }

i want to retrieve ChatData user = dataSnapshot.getValue(ChatData.class); userChild.add(user);

Debug time : 

         DataSnapshot { key = 
                     1123469ACDEFFFFGJKLNOOOPQSTUUVWZabccdehhkkloopqruuuuwxyy, 
                     value
                           = {-LrjsM3ZO0pzQbvCcRuQ
                           ={time=Tue Oct 22 00:53:10 GMT+05:00 2019
                           , msg=hi
                            , user_ID=LuFro93OCcPEpoFTKuQhUkeuw462}} 
                              }


How to get this Value

Database Image

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

In your first example, the Firebase client handles the list, and calls your onChildAdded for each result. But with a ValueEventListener, you get a single snapshot with all results. So your onDataChange will need to handle this list, which you do by iterating over the DataSnapshot.getChildren().

Something like this:

myRef.orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
            ChatData user = userSnapshot.getValue(ChatData.class);
            userChild.add(user);
        }
    }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807