[英]Android RecyclerView database remove item
我正在嘗試從SQLite DB填充的RecyclerView列表中刪除項目,並收到此錯誤:
java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1
我正在嘗試的代碼正在使用未從SQLite數據庫填充的數據,但是在這種情況下,長時間單擊它會崩潰。 這是我的代碼:
@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);
}
誰能幫我這個?
解
我在removeData()
弄亂了這個db.Todo
,它應該像inicialisation一樣是listData
。
該錯誤表明在infoData
中找不到dbTodo
因此indexOf
返回-1
,因此在您的dbTodo
行中,您刪除了索引-1
(這顯然超出了范圍)。 要消除此錯誤,您必須在嘗試刪除infoData
之前僅檢查它是否存在。
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?
}
}
我希望這可以幫助你。
很明顯,您試圖用來獲取物品的位置是不正確的。
dbTodo.indexOf(infoData)
如果找不到infoData對象,則返回-1,因此您必須選擇:1)在嘗試從數據庫中刪除對象之前檢查位置
if(position >= -1){
dbTodo.remove(position);
......
2)在嘗試刪除infoData之前,請確保它確實在數據庫中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.