数据库ID和列表视图项ID是离散的

时间:2015-08-19 13:18:11

标签: android sqlite android-listview

    I am getting stuck with the issue 
    I am getting the All messages from database and shows in list, list having check boxes when I pressed delete then checked check box deleted from database.

       And when I am again click to see all message then all position of the message's get changed but in the database id remain same and further i delete some message then message from database not deleted because position id and database message id become different.

    Please give me any suggestion to solve this issue thank you in advance...
  • 这是我的代码点击位置并将此位置发送到数据库,但下次删除时数据库ID不同。

        OnClickListener listenerDel = new OnClickListener() {
                @Override
                public void onClick(View v) {
                    /** Getting the checked items from the listview */
                    SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
                    int itemCount = getListView().getCount();
    
                    for(int i=itemCount-1; i >= 0; i--){
                        if(checkedItemPositions.get(i)){
                            Log.e("position",""+(i+1));
    
    
                            adapter.remove(list.get(i));
                            db.deleteMessage(i);
                        }
                    }   
    //              checkedItemPositions.clear();
                    adapter.notifyDataSetChanged();
    
    
    
                }
            };            
    

1 个答案:

答案 0 :(得分:1)

如果您有一个大型列表而且ID不一致,则使用迭代器删除时可能会出现问题。尝试在数据库适配器中编写一个函数,它接受项本身而不是for循环的迭代器,如下所示:

public void deleteItem(Item item){
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_ITEMS, KEY_ID + " = ?",
            new String[]{String.valueOf(item.getID())});
    db.close();
}