问题描述
当我尝试从addChildListerner(DataSnapShot)获取对象时,它工作正常并分配给对象的DataSnapshot
When i try to get a Object from addChildListerner(DataSnapShot) it works fine and assign to DataSnapshot to object
工作正常:
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);
但是当我尝试使用ValueListerner(snapshot)应用程序崩溃获取相同的对象时我已经使用了snapshot.getChildern ()
snapshot.getValue
的所有内容,然后应用崩溃了.
But when i try to get same Object using ValueListerner(snapshot) app crashi have use everything snapshot.getChildern ()
snapshot.getValue
then app crash.
错误
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);
}
我想找回 ChatData用户= 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}}
}
如何获取此值
推荐答案
对Firebase数据库执行查询时,可能会有多个结果.因此,快照包含这些结果的列表.即使只有一个结果,快照也会包含一个结果的列表.
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.
在您的第一个示例中,Firebase客户端处理列表,并为每个结果调用您的onChildAdded
.但是使用ValueEventListener
,您将获得包含所有结果的单个快照.因此,您的onDataChange
将需要处理此列表,方法是遍历DataSnapshot.getChildren()
.
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()
.
类似这样的东西:
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);
}
}
这篇关于对象未使用valueEventListerner从Datasnapshot获取,但工作正常,但是AddChildEventListern的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!