我正在尝试从数据库中检索注释,但是它将所有注释显示为重复
该列表器可以很好地处理片段,但是在Activity上实现时会出现重复的项目错误
private void startListening() {
Query query = mCommentsDatabase;
FirebaseRecyclerOptions<Comment> options =
new FirebaseRecyclerOptions.Builder<Comment>()
.setQuery(query, Comment.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Comment, CommentsViewHolder>(options){
@Override
public CommentsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.single_comment_item, parent, false);
return new CommentsViewHolder(view);
}
@Override
protected void onBindViewHolder(final CommentsViewHolder holder, int position, final Comment model) {
mCommentsDatabase.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
if (dataSnapshot.exists() && dataSnapshot != null){
if (dataSnapshot.exists()){
String CommenterId = dataSnapshot.child("uid").getValue().toString();
mUsersDatabase.child(CommenterId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot userDataSnapshot) {
if (userDataSnapshot.exists()){
String username = userDataSnapshot.child("username").getValue().toString();
String thumbImage = userDataSnapshot.child("profile_thumbnail").getValue().toString();
String comment = dataSnapshot.child("body").getValue().toString();
Long timestamp = Long.parseLong(dataSnapshot.child("timestamp").getValue().toString());
GetTimeAgo getTimeAgo = new GetTimeAgo();
String time = getTimeAgo.getTimeAgo(timestamp, getApplicationContext());
holder.setName(username);
holder.setComment(comment);
holder.setImage(thumbImage, getApplicationContext());
holder.setTime(time);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
};
mCommentsList.setAdapter(adapter);
adapter.startListening();
}
有人可以帮忙指出问题所在吗?
我已经在工作中的片段中实现了相同的功能,但是当在Activity中使用时,效果却很奇怪。