Object not getting From Datasnapshot using valueEventListerner but Working find but AddChildEventListern

为君一笑 提交于 2020-01-25 07:20:13

问题


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


回答1:


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);
        }
    }


来源:https://stackoverflow.com/questions/58499651/object-not-getting-from-datasnapshot-using-valueeventlisterner-but-working-find

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!