I'm trying to remove item from RecyclerView list that is populated from SQLite DB and getting this error:
java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1
The code I'm trying with is working with data that's not populated from SQLite database, but in this case it crashes on long click. Here's my code:
@Override
public void onBindViewHolder(RecHolder holder, final int position) {
final Todo item = listData.get(position);
final int currentPosition = position;
final Todo infoData = listData.get(position);
holder.container.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
removeData(infoData);
return true;
}
});
}
private void removeData(Todo infoData) {
int position = dbTodo.indexOf(infoData);
dbTodo.remove(position);
notifyItemRemoved(position);
}
Can anyone help me with this?
SOLUTION
I've messed up with this db.Todo
in removeData()
, it should be listData
like in inicialisation.
The error signifies that infoData
is not found in the dbTodo
- hence indexOf
returns -1
, and so in your subsequent line, you remove something at index -1
(which is obvisouly out of bounds). To get rid of this error, you must just check that infoData
does exist before trying to remove it.
private void removeData(Todo infoData) {
int position = dbTodo.indexOf(infoData);
//here you check that it exists before you try to remove it
if(position >= -1){
dbTodo.remove(position);
notifyItemRemoved(position);
}
else{
//do something else here?
}
}
I hope this helps you.
It is clear that position you tried to use to get item from is incorrect.
dbTodo.indexOf(infoData)
return you -1 if it didn't find infoData object, so you have to choices: 1) Check position before trying to remove object from database
if(position >= -1){
dbTodo.remove(position);
......
2) Check infoData is really in database before trying to remove it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.