我已经从ListView切换到RecyclerView,我使用Firebase中的数据动态添加RecyclerView项目。但是,我无法成功生成RecyclerView。
目前,屏幕为空白,并且没有CardView项目添加到视图中。我假设我的RecyclerView适配器存在问题。
我的监听器,我在这里添加到mCommentArrayList,然后在我的RecyclerView适配器中从这些数据中提取:
mUpdateRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
setImage(dataSnapshot);
setQuestion(dataSnapshot);
createInitialCommentIDArray(dataSnapshot);
mNumberOfCommentsAtPoll = (int) dataSnapshot.child(COMMENTS_LABEL).getChildrenCount();
for (int i = 0; i < mNumberOfCommentsAtPoll; i++) {
String commentID = (String) dataSnapshot.child(COMMENTS_LABEL).child(mCommentIDArrayList.get(i)).child("COMMENT").getValue();
Log.v("COMMENT_ID", "The comment ID is " + commentID);
String userID = (String) dataSnapshot.child(COMMENTS_LABEL).child(mCommentIDArrayList.get(i)).child("USER_ID").getValue();
Log.v("USER_ID", "The user ID is " + userID);
mCommentArrayList.add(0 , new Comments(mUserAvatar, userID, commentID));
mCommentAdapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
这是我的RecyclerView适配器:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
protected ImageView userAvatar;
protected TextView userID;
protected TextView userComment;
public ViewHolder(View v) {
super(v);
userAvatar = (ImageView) findViewById(R.id.profile_image_avatar);
userID = (TextView) findViewById(R.id.user_ID);
userComment = (TextView) findViewById(R.id.user_comment);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(ArrayList<Comments> myDataset) {
mCommentArrayList = myDataset;
}
// Create new views (invoked by the layout manager)
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.individual_comment, parent, false);
// set the view's size, margins, paddings and layout parameters
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.userComment.setText(mCommentArrayList.get(position).getUserComment());
holder.userID.setText(mCommentArrayList.get(position).getUserID());
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mNumberOfCommentsAtPoll;
}
}
答案 0 :(得分:3)
在RecycleViewAdapter
的getItemCount()中,您应该返回列表数据源大小
@Override
public int getItemCount() {
return mCommentArrayList.size();
}
答案 1 :(得分:0)
主要问题涉及我的findViewByID()方法。
{{1}}
我使用v.findViewByID()来解决问题并消除我遇到的所有数据填充问题。