简体   繁体   English

当数组中没有项目时,RecyclerView OutOfBoundsException

[英]RecyclerView OutOfBoundsException When No Items in Array

I am trying to create a RecyclerView that populates CardViews based on data in Firebase. 我正在尝试创建一个RecyclerView,它基于Firebase中的数据填充CardViews。 I am receiving an IndexOutOfBoundsException when there is no data in Firebase, however I would like for the RecyclerView to display (without any data) when there is no data in Firebase: 当Firebase中没有数据时,我会收到IndexOutOfBoundsException,但是当Firebase中没有数据时,我希望RecyclerView显示(不包含任何数据):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Firebase.setAndroidContext(this);
    setContentView(R.layout.activity_discussion);
    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);
    setTitle(R.string.discussion_title_text);

    mDateFormat = new SimpleDateFormat("MM-dd-yyyy");
    mDate = new Date();
    mCurrentDateString = mDateFormat.format(mDate);

    mBaseRef = new Firebase(FIREBASE_URL);
    mPollsRef = mBaseRef.child(POLLS_LABEL);
    mUpdateRef = mPollsRef.child(mCurrentDateString).child(String.valueOf(mPollIndex + 1));
    mCommentsRef = mUpdateRef.child(COMMENTS_LABEL);

    mPollImage = (ImageView) findViewById(R.id.comments_image);
    mPollCommentQuestion = (TextView) findViewById(R.id.poll_comment_question);
    mUserComment = (EditText) findViewById(R.id.user_comment);
    mUserAvatar = (ImageView) findViewById(R.id.profile_image_avatar);

    mCommentArrayList = new ArrayList<Comments>();
    mCommentIDArrayList = new ArrayList<String>();


    mPollCommentsList = (RecyclerView) findViewById(R.id.poll_comments_list);
    LinearLayoutManager llm = new LinearLayoutManager(this);
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    mPollCommentsList.setLayoutManager(llm);
    mPollCommentsList.setHasFixedSize(true);

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

    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) {

        }
    });

    mCommentAdapter = new MyAdapter(mCommentArrayList);
    mPollCommentsList.setAdapter(mCommentAdapter);


    Intent intent = getIntent();
    String pollID = intent.getStringExtra("POLL_ID");
    mPollIndex = intent.getIntExtra("POLL_INDEX", 0);


    //TODO: Store unique comment ID's in an array

    //TODO: Figure out how to programmatically add images to AWS and then store URL in Firebase
    ImageView fab = (ImageView) findViewById(R.id.add_comment);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            HashMap<String, Object> commentMap = new HashMap<String, Object>();
            commentMap.put("USER_ID", mBaseRef.getAuth().getUid());
            commentMap.put("COMMENT", mUserComment.getText().toString());
            mUpdateRef.child(COMMENTS_LABEL).push().updateChildren(commentMap);
            hideKeyboard(view);
            mUserComment.setText("");
            Toast.makeText(getApplicationContext(), R.string.comment_added, Toast.LENGTH_LONG).show();
        }
    });
}

My Array Adapter, I note where the error is occurring: 我的阵列适配器,我注意到发生错误的位置:

 public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private ArrayList<Comments> mDataSet;

    // 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) {
        mDataSet = 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
        ViewHolder x = new ViewHolder(v);

        return x;
    }

    // Replace the contents of a view (invoked by the layout manager)

    //The OutOfBoundsException is pointing here
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
            holder.userComment.setText(mCommentArrayList.get(position).getUserComment());
            String x = mCommentArrayList.get(position).getUserComment();
            Log.v("ON_BIND_VIEW", "THE STRING IS " + x);
        }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mNumberOfCommentsAtPoll;
    }
}

Result: 结果: 在此处输入图片说明

您应该尝试在getItemCount()方法而不是mNumberOfCommentsAtPoll中返回mDataset.size()。

@Override public int getItemCount() { return mDataSet.size(); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM