无法解决以下问题。我有SQLite数据库中保存的项目列表和项目名称。我使用onContextItemSelected方法来操作列表中的项目(添加和删除)。到目前为止,没有问题添加到数据库新名称并反映列表中的新项目;但删除让我发疯。当我单击删除时,项目将从列表中删除,但无法从数据库中删除名称。
这是代码
if (item.getItemId() == CM_DELETE_ID) {
AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
// delete item from list
bazar.remove(acmi.position);
// get clicked item id from list
rowID = acmi.id;
// open database
datasource.openToWrite();
if (cursor != null) {
Log.d(LOG_TAG, "--- Delete from mytable: ---");
//delete from database
datasource.db.delete(DBHelper.TABLE, DBHelper.COLUMN_ID + " = " + rowID, null);
Log.d(LOG_TAG, "deleted row = " + datasource.db.delete(DBHelper.TABLE, DBHelper.COLUMN_ID + " = " + rowID, null));
} else {
Log.d(LOG_TAG, "Cursor is null");
cursor.close();
}
// close database
datasource.close();
myAdapter.notifyDataSetChanged();
return true;
日志说
05:12:08.403 1131 example.CustomAdapter DEBUG row inserted, ID = 1
05:12:08.413 1131 example.CustomAdapter DEBUG ID = 1, name = A1
05:12:22.853 1131 example.CustomAdapter DEBUG row inserted, ID = 2
05:12:22.864 1131 example.CustomAdapter DEBUG ID = 1, name = A1
05:12:22.864 1131 example.CustomAdapter DEBUG ID = 2, name = A2
05:12:23.623 111 jp.co.omronsoft.openwnn DEBUG dalvikvm GC_EXTERNAL_ALLOC freed 20K, 44% free 3471K/6151K, external 3902K/3936K, paused 169ms
05:12:41.833 1131 example.CustomAdapter DEBUG --- Delete from mytable: ---
05:12:41.984 1131 example.CustomAdapter DEBUG deleted row count = 0
在onCreate中我有dbReadAll方法,它列出了我拥有的所有项目和bazar.add(new Bazar(names,R.drawable.unread));是我的ArrayList
void dbReadAll() {
bazar.add(new Bazar(names, R.drawable.unread));
// подключаемся к базе данных для чтения данных
datasource.openToRead();
// получаем значение курсора
cursor = datasource.queryAll();
if (cursor.moveToFirst()) {
nameColIndex = cursor.getColumnIndex(DBHelper.COLUMN);
do {
Log.d(LOG_TAG, "ID = " + cursor.getInt(idColIndex) + ", name = " + cursor.getString(nameColIndex));
names = cursor.getString(nameColIndex);
bazar.add(new Bazar(names, R.drawable.unread));
} while (cursor.moveToNext());
} else {
cursor.close();
datasource.close();
}
}
答案 0 :(得分:0)
试试这个:
//delete from database
datasource.db.delete(DBHelper.TABLE, DBHelper.COLUMN_ID + "=?", new String[]{Long.toString(rowID)});
似乎删除语句使用预先准备的查询有关详细信息,请参阅this sof question
更新将rowId
更改为Long.toString(rowId)
我们需要在字符串数组中输入字符串
答案 1 :(得分:0)
我认为你正在映射行id错误,rowid可能不等于acmi.id。
所以你可以做的是从游标
获取行IDcursor.movetoPosition(acme.id);
rowid = cursor.getLong(cursor.getColumnIndex(DBHelper.COLUMN_ID))