ChildEventListener必须实现onChildChanged [英] ChildEventListener must implement onChildChanged
问题描述
这让我发疯.我使用的是"onChildAdded",如果我将其切换为"onChildChanged",它会要求我切换回"onChildAdded".我不知道为什么要这么做.
This is driving me insane. I'm using "onChildAdded" and if I switch it to "onChildChanged" then it asks me to switch back to "onChildAdded". I have no idea why it's doing this.
这是我的代码:
Query queryRecycler = mDatabase.limitToLast(5);
queryRecycler.addChildEventListener(new ChildEventListener() {
public void onChildAdded(DataSnapshot dataSnapshot, String previousKey) {
messageList.add(dataSnapshot.getValue(Message.class));
mMessageAdapter.notifyDataSetChanged();
}
});
以及完整的错误:
类从ChildEventListener派生的匿名类"必须是 声明抽象或实现抽象方法 'ChildEventListener'中的'onChildChanged(DataSnapshot,String)'
Class 'Anonymous class derived from ChildEventListener' must either be declared abstract or implement abstract method 'onChildChanged(DataSnapshot, String)' in 'ChildEventListener'
推荐答案
如果要实现 ChildEventListener ,则应覆盖onChildAdded,onChildChanged,onChildRemoved,onChildMoved.即使您不想要它. (来自 firebase 的代码示例)
If you want to implement ChildEventListener, you should override onChildAdded,onChildChanged, onChildRemoved, onChildMoved. even you do not want it. (Code example from firebase)
ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// A new comment has been added, add it to the displayed list
Comment comment = dataSnapshot.getValue(Comment.class);
// ...
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so displayed the changed comment.
Comment newComment = dataSnapshot.getValue(Comment.class);
String commentKey = dataSnapshot.getKey();
// ...
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so remove it.
String commentKey = dataSnapshot.getKey();
// ...
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
// A comment has changed position, use the key to determine if we are
// displaying this comment and if so move it.
Comment movedComment = dataSnapshot.getValue(Comment.class);
String commentKey = dataSnapshot.getKey();
// ...
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
Toast.makeText(mContext, "Failed to load comments.",
Toast.LENGTH_SHORT).show();
}
};
ref.addChildEventListener(childEventListener);
这篇关于ChildEventListener必须实现onChildChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!