android - 如何调用Database Helper类的Delete方法?

标签 android database sqlite android-sqlite

我想在我的数据库助手类中使用下面给出的删除方法。我问了 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/

相关文章:

android - 工具栏图像居中

android - 如何在 Android 中获取电话联系人

php - 如何合并到数据库

android - SQLiteOpenHelper onCreate()/onUpgrade() 什么时候运行?

android - 有一个我从 Iphone 项目 (.sqlite) 获得的数据库

python - SQlite UPDATE WHERE语法错误

Android:NetworkInfo.isConnected() 上的 NullPointerException 与 Firebase

android - 仅在 Android Gmail 中的电子邮件中出现空白。我该如何解决这个问题?

database - MongoDB信息请求

database - 在 apache cassandra 上进行通配符搜索有什么技巧吗?