【问题标题】:ChildEventListener must implement onChildChangedChildEventListener 必须实现 onChildChanged
【发布时间】:2019-07-20 17:49:26
【问题描述】:
这让我发疯了。我正在使用“onChildAdded”,如果我将其切换到“onChildChanged”,那么它会要求我切换回“onChildAdded”。我不知道它为什么这样做。
这是我的代码:
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)'
【问题讨论】:
标签:
android
firebase-realtime-database
【解决方案1】:
如果你想实现ChildEventListener,你应该重写onChildAdded、onChildChanged、onChildRemoved、onChildMoved。即使你不想要它。 (来自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);
【解决方案2】:
您可能希望在实现的方法.onChildChanged() 中添加@Override 注释,否则它不会被识别为abstract 方法的实现。 documentation 内容如下:
表示方法声明旨在覆盖超类型中的方法声明。