从RecyclerView删除项目时出现问题

时间:2019-02-25 05:50:36

标签: android android-recyclerview recycler-adapter

当我单击回收器项目中的关闭按钮时,应用程序崩溃并引发错误。我的代码如下:

public void remove(int position) {
    asset_type.remove(position);
    asset_count.remove(position);
    asset_value.remove(position);
    AssetDetailsActivity.assetValueId.remove(position);
    AssetDetailsActivity.assetCountId.remove(position);
    AssetDetailsActivity.assetTypeId.remove(position);
    notifyItemRemoved(position);

}

我的错误日志,并且在回收者视图中有2个以上的物品

2019-02-25 11:04:16.733 5036-5036/com.tachyloans E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.tachyloans, PID: 5036
    java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
        at java.util.ArrayList.remove(ArrayList.java:503)
        at com.tachyloans.common.MyAdapter.remove(MyAdapter.java:62)
        at com.tachyloans.common.MyAdapter$2.onClick(MyAdapter.java:113)
        at android.view.View.performClick(View.java:6310)
        at android.view.View$PerformClick.run(View.java:24970)
        at android.os.Handler.handleCallback(Handler.java:794)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:6656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

1 个答案:

答案 0 :(得分:0)

这是因为您尝试依次删除List.remove(position)中的某些项目。您可能会使用以下代码删除相同的商品位置:

asset_type.remove(position);
asset_count.remove(position);
asset_value.remove(position);
AssetDetailsActivity.assetValueId.remove(position);
AssetDetailsActivity.assetCountId.remove(position);
AssetDetailsActivity.assetTypeId.remove(position);

问题的根源通常是因为您忘记了总是通过引用传递非原始数据类型,例如:List

在以下典型的RecylerView适配器中,列表(List<YourDatum> data)通过引用传递:

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

    ..

    private List<YourDatum> mData;

    public YourAdapter(List<YourDatum> data) {
        mData = data;
    }
}

,通常我们通过构造函数将List传递给:

public class YourActivity extends AppCompatActivity {

     ArrayList<YourDatum> mData;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         // ...

         // assuming that createInitializeData(10) will create 10 data
         mData = createInitializeData(10);

         // Now we're passing the data to adapter.
         YourAdapter adapter = new YourAdapter(mData);
         ...
     }
}

因此,YourActivity.mDataYourAdapter.mData都指向相同的位置。因此,每当您从YourActivity.mData删除项目时,YourAdapter.mData项也会被删除。

现在,您只需要为您的案例使用以下代码:

asset_type.remove(position);
asset_count.remove(position);
asset_value.remove(position);

// the following is not needed because it's incorrect
// AssetDetailsActivity.assetValueId.remove(position);
// AssetDetailsActivity.assetCountId.remove(position);
// AssetDetailsActivity.assetTypeId.remove(position)