Reputation: 2157
I received an error from Google Play console:
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)
I understand that the app tries to work with wrong index and as a result it receives the crash. The problem is placed at this method:
private fun removeItem(position: Int) {
records.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, records.size)
}
this method can be called when the used tries to remove an item from the certain list. I tried to replace removeAt
by remove
but I got a strict suggestion to use removeAt
. Maybe I can check when position doesn't equal to -1 or this is a bad idea?
remove item method call:
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) {
}
})
Upvotes: 0
Views: 474
Reputation: 15433
Try checking position inclusive with collections before perform delete operation.
private fun removeItem(position: Int) {
if(position < 0 || position >= records.size)
return
records.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, records.size)
}
Upvotes: 1