Android RecyclerView : notifyDataSetChanged() IllegalStateException

前端 未结 22 1783
天涯浪人
天涯浪人 2020-11-28 02:57

I\'m trying to update the items of a recycleview using notifyDataSetChanged().

This is my onBindViewHolder() method in the recycleview adapter.

@Over         


        
22条回答
  •  时光取名叫无心
    2020-11-28 03:49

    I ran into this exact issue! After Moonsoo's answer didn't really float my boat, I messed around a bit and found a solution that worked for me.

    First, here's some of my code:

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
    
        final Event event = mDataset.get(position);
    
        //
        //  .......
        //
    
        holder.mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                event.setActive(isChecked);
                try {
                    notifyItemChanged(position);
                } catch (Exception e) {
                    Log.e("onCheckChanged", e.getMessage());
                }
            }
        });
    

    You'll notice I'm specifically notifying the adapter for the position I'm changing, instead of the entire dataset like you're doing. That being said, although I can't guarantee this will work for you, I resolved the problem by wrapping my notifyItemChanged() call in a try/catch block. This simply caught the exception, but still allowed my adapter to register the state change and update the display!

    Hope this helps someone!

    EDIT: I'll admit, this probably is not the proper/mature way of handle the issue, but since it doesn't appear to be causing any problems by leaving the exception unhandled, I thought I'd share in case it was good enough for someone else.

提交回复
热议问题