我这样从我的RecyclerView中删除​​了一个项目:

@Override
public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
    final int position = viewHolder.getAdapterPosition(); //get position which is swipe

    if (direction == ItemTouchHelper.LEFT) {    //if swipe left
        activeSubs.remove(position);
        adapter.notifyItemRemoved(position);
        adapter.notifyItemRangeChanged(position, activeSubs.size());
        saveListToSharedPrefs();
        updateCost();
    }
}


其中activeSubs是自定义对象的ArrayList<>

当我从列表中删除元素时,应用程序崩溃,这是我的日志:

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
                      at java.util.ArrayList.get(ArrayList.java:437)
                      at com.dancam.subscriptions.ActiveSubscriptions.ActiveSubsRecyclerAdapter.onBindViewHolder(ActiveSubsRecyclerAdapter.java:58)


ActiveSubsRecyclerAdapter.java:58-此行指向onBindViewHolder()的第一行,如下所示:

@Override
public void onBindViewHolder(ActiveViewHolder viewHolder, int pos) {
    Subscription sub = activeSubsList.get(pos);
    viewHolder.title.setText(sub.getTitle());
    viewHolder.cycle.setText(cycleArray[sub.getCycle()]);
    viewHolder.duration.setText(durationArray[sub.getDuration()]);
    viewHolder.price.setText(String.valueOf(sub.getPrice()).concat(currency.getSymbol()));
    viewHolder.firstBill.setText(sub.getFirstPayment());
    viewHolder.relativeLayout.setBackgroundColor(mContext.getResources()
                .getColor(sub.getColor()));
    viewHolder.expandableLayout.setBackgroundColor(mContext.getResources()
                .getColor(sub.getColor()));
    Picasso.with(mContext).load(sub.getImage()).into(viewHolder.image);
}


我尝试在此行上设置断点,这是调试输出:

java - Android RecyclerView-onBindViewHolder中的IndexOutOfBounds异常-LMLPHP

有关如何解决此问题的任何线索?

最佳答案

我在这里看到两个不同的列表。一个是activeSubs,另一个是activeSubsList。您正在使用哪一个来填充RecyclerView

无论如何,您需要在ArrayList中使用一个RecyclerView进行填充,以便可以跟踪该ArrayList的状态,并通过RecyclerView调用相应地更新notifyDataSetChanged()

我建议仅使用activeSubs列表,并在从列表中获取内容时也在onBindViewHolder函数中使用它。

当您的onBindViewHolder被调用时,我假设您的getCount()函数返回的activeSubs大小实际上不是空的,因此onBindViewHolder中的调用获取了IndexOutOfBoundException

因此,我只是在下面重写您的一些代码。

if (direction == ItemTouchHelper.LEFT) {    //if swipe left
    activeSubs.remove(position);
    saveListToSharedPrefs();
    updateCost();

    // Only calling notifyDataSetChanged should do the job
    adapter.notifyDataSetChanged();
}


现在,在您的onBindViewHolder函数中,您需要从activeSubs列表中获取对象。

@Override
public void onBindViewHolder(ActiveViewHolder viewHolder, int pos) {
    Subscription sub = activeSubs.get(pos);
    // ... Here goes the other code
}


并且getCount函数应返回activeSubs列表的大小。

public int getItemCount () {
    return (activeSubs != null) ? activeSubs.size() : 0;
}

关于java - Android RecyclerView-onBindViewHolder中的IndexOutOfBounds异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46631751/

10-12 04:41