【发布时间】:2016-05-24 01:53:25
【问题描述】:
我已从 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;
}
}
【问题讨论】:
-
我在您的
getItemCount()中看到您返回mNumberOfCommentsAtPoll。但我看不到您在MyAdapter中声明mNumberOfCommentsAtPoll的位置。 -
我知道这不是问题,但感谢您指出
标签: android xml firebase android-recyclerview