【问题标题】:Index out of bound: ArrayList索引超出范围:ArrayList
【发布时间】:2019-03-25 17:27:05
【问题描述】:

问题

我已经使用外部库为回收站视图实现了多选行为。现在,为了从回收站视图中删除项目,我实现了两个 for 循环。第一个 for 循环从 SQLite 中删除项目,第二个 for 循环从适配器中删除对应的视图。但是,从适配器中删除视图时会出现问题。

         for (i in selectedCardItems!!.indices)  //selectedCardItems stores selected card position.
            {
                val index = selectedCardItems!![i]
                val noteRowID = listItems!![index]  //list items contains references to items in SQLite and is fed to recyclerview.setadapter = myAdapter(context,listitems)


                dbHandler!!.deleteNote(noteRowID.noteID!!)
            }




            for(i in selectedCardItems!!.indices)
            {
                val index = selectedCardItems!![i]
                listItems!!.removeAt(i)  //problem starts here, due to mismatched indexes.

                adapter!!.notifyItemRemoved(i)
            }

            if(dbHandler!!.trashedNotesCount() == 0)
            {
                trashedRecyclerView!!.visibility = View.GONE
                emptyTrashImg!!.visibility = View.VISIBLE
                emptyTrashMsg!!.visibility = View.VISIBLE
            }

            selectedCardItems!!.clear()  //once all operation is done,remove card positions from this ArrayList.
        }

listitems 和 selectedCardPosition 都是 ArrayList 类型。我知道一旦从索引中删除了 ArrayList 中的项目,则较高的索引项目索引会自动移动到较低的索引。解决此问题的有效方法是什么?

我尝试了什么: BAD 修复基本上是删除删除视图的第二个 for 循环,并将其替换为同样删除删除动画的 adapter.notifyDataSetChanged()。

【问题讨论】:

  • selectedCardItems 中保存要删除的项目的索引?
  • 是的,它包含要删除的项目的索引。

标签: android arraylist kotlin


【解决方案1】:

如果我正确理解您的问题,问题就出现了,因为从列表中删除会破坏初始索引。如果是这种情况,您必须从较高的索引开始删除,然后再往下走。所以在循环之前对列表进行降序排序:

selectedCardItems!!.sortDescending() 

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 2017-07-30
    • 2020-02-13
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    相关资源
    最近更新 更多