我想在我的数据库助手类中使用下面给出的删除方法。我问了 2 次,但没有收到这样的回复。这是我从 androidhive.info 中获取的处理程序类
删除方法(在 DatabaseHandler 文件中):
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",new String[] { String.valueOf(contact.getID()) });
db.close();
}
当我在另一个 Activity 中实现它时。像这样:
String a = Integer.toString(_contactlist.get(position).getID());
viewHolder.txtid.setText(a.trim());
viewHolder.txt_name.setText(_contactlist.get(position).getName().trim());
viewHolder.txt_phone.setText(_contactlist.get(position).getPhoneNumber().trim());
final int temp = position;
Contact pm = db.getContact(temp); //temp is the position of the contact
db.deleteContact(pm);
但是当我使用它时出现意外错误,即它只删除行中的 1 个数据而不是所选数据。
我的getContact 方法:
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
最佳答案
尝试使用 where 子句给出完整的查询。而不是
db.delete(TABLE_CONTACTS, KEY_ID + "= ?",new String[] { String.valueOf(contact.getID()) });
使用
db.execSQL("delete * from TABLE_CONTACTS where KEY_ID = "+contact+";");
前提是contact是整型变量。
关于android - 如何调用Database Helper类的Delete方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18347449/