我从Google Play控制台收到错误消息:

FATAL EXCEPTION: ControllerMessenger
Process: my_package, PID: 19868
java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
    at java.util.ArrayList.remove(ArrayList.java:405)
    at my_package.notepad.utils_adapters.NotesAdapter.removeItem(NotesAdapter.kt:251)
    at my_package.notepad.utils_adapters.NotesAdapter.access$removeItem(NotesAdapter.kt:25)
    at my_package.notepad.utils_adapters.NotesAdapter$deleteNote$1.onResponse(NotesAdapter.kt:231)


我了解该应用尝试使用错误的索引,因此收到崩溃信息。问题在于此方法:

private fun removeItem(position: Int) {
        records.removeAt(position)
        notifyItemRemoved(position)
        notifyItemRangeChanged(position, records.size)
    }


当用户尝试从特定列表中删除项目时,可以调用此方法。我试图用removeAt替换remove,但是我强烈建议使用removeAt。也许我可以检查一下位置不等于-1还是一个坏主意?

更新

删除项目方法调用:

private fun deleteNote(id: Int?, context: Context, position: Int) {
        Singleton.apiService().deleteNote("Bearer " + context.getSharedPreferences("app_data", 0).getString("access_token", ""), id).enqueue(object : Callback<NoteAction> {
            override fun onResponse(call: Call<NoteAction>, response: Response<NoteAction>) {
                if (response.isSuccessful) {
                    Toast.makeText(context, "Successfully deleted", Toast.LENGTH_SHORT).show()
                    removeItem(position)
                } else {
                    try {
                        val jObjError = JSONObject(Objects.requireNonNull<ResponseBody>(response.errorBody()).string())
                        Singleton.error["message"] = jObjError.getString("message")
                        Singleton.error["request_no"] = "19"
                        Singleton.workingWithErrors(Singleton.error, context)
                    } catch (e: Exception) {

                    }
                }
            }

            override fun onFailure(call: Call<NoteAction>, t: Throwable) {
            }

        })

最佳答案

在执行删除操作之前,请尝试检查包含集合的位置。

private fun removeItem(position: Int) {
    if(position < 0 || position >= records.size)
        return

    records.removeAt(position)
    notifyItemRemoved(position)
    notifyItemRangeChanged(position, records.size)
}

07-28 02:21