RecyclerView array out-of-bounds exception java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position

1. Description of the situation:

When testing the music app, repeatedly plugging and unplugging multiple USB disks to test playback, this bug may appear: java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position

2. Reasons for BUG occurrence:

When removing and adding data, be sure to ensure that the data in the Adapter is consistent with the removed data! What does it mean? That is, if you update your collection and call the new notifyxxxx method of the Adapter, the adapter's expected update result is different from the actual collection update result, then an exception will occur.

Data consistency actually means ensuring that the quantities are consistent. That is to say, the Adapter has a size, and your collection has a size. These two sizes must remain the same when calling notifyxxxx of the Adapter.

Repeatedly inserting and removing the USB flash drive triggers automatic audio scanning, which may cause the size of the collection list to change, but an error occurs when the Adapter is not notified in time to refresh the data.

3.Solution:

1). Solution 1: Separate the collection list and the adapter’s list

public void setMusicInfoList(List<MusicBean> musicList) {
        try {
            //此处list不直接赋值,赋值外层list有变化后未及时通知adapter刷新数据
            if (musicInfoList == null){
                musicInfoList = new ArrayList<>();
            }
            if (musicList != null){
                musicInfoList.clear();
                musicInfoList.addAll(musicList);
            }

            
            notifyDataSetChanged();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

2). Solution 2: The most direct and effective solution is to overwrite the LinearLayoutManager class. The code is as follows:

public class RecyclerViewNoBugLinearLayoutManager extends LinearLayoutManager {
    public RecyclerViewNoBugLinearLayoutManager(Context context) {
        super( context );
    }
 
    public RecyclerViewNoBugLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super( context, orientation, reverseLayout );
    }
 
    public RecyclerViewNoBugLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super( context, attrs, defStyleAttr, defStyleRes );
    }
 
    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        try {
        //try catch一下
            super.onLayoutChildren( recycler, state );
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }
 
    }
}

Guess you like

Origin blog.csdn.net/yzwfeng/article/details/132046976
Recommended