如何删除android sqlite中的单行

时间:2015-07-01 12:55:47

标签: android sqlite

sqlite ListView上有CustomListAdapter alert dialogue数据。点击一行会弹出sqlite,提示用户删除private void deleteDialog() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyCart.this); alertDialog.setCancelable(false); alertDialog.setMessage("Delete item?"); alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { myDb.deleteSingleContact(toString()); } }); alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } 中的单行。 {1}}在我的活动中:

 public void deleteSingleContact(String title){

        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(CONTACTS_TABLE_NAME, CONTACTS_COLUMN_TITLE + "=?", new String[]{title});
//KEY_NAME is a column name
    }

在我的DBHelper.java上:

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "MyDBName.db";
    public static final String CONTACTS_TABLE_NAME = "contacts";
    public static final String CONTACTS_COLUMN_ID = "id";
    public static final String CONTACTS_COLUMN_TITLE = "title";
    public static final String CONTACTS_COLUMN_AMOUNT = "amount";
    public static final String CONTACTS_COLUMN_DESC = "description";

    private HashMap hp;

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(
                "create table contacts " +
                        "(id integer primary key, title text,amount float,description text)"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    }

    public boolean insertContact(String title,  float amount, String description) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put("title", title);
        contentValues.put("amount", amount);
        contentValues.put("description", description);


        db.insert("contacts", null, contentValues);
        return true;
    }

    public Cursor getData(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from contacts where id=" + id + "", null);
        return res;
    }

    public int numberOfRows() {
        String countQuery = "SELECT  * FROM " + CONTACTS_TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        int cnt = cursor.getCount();
        cursor.close();
        return cnt;
    }

    public boolean updateContact(Integer id, String title, float amount, String description) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("title", title);
        contentValues.put("amount", amount);
        contentValues.put("description", description);

        db.update("contacts", contentValues, "id = ? ", new String[]{Integer.toString(id)});
        return true;
    }

    public void deleteContact() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete("contacts", null, null);
        db.close();
    }

    public void deleteSingleContact(String title){

        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(CONTACTS_TABLE_NAME, CONTACTS_COLUMN_TITLE + "=?", new String[]{title});
//KEY_NAME is a column name
    }

    public boolean checkForTables() {
        boolean hasRows = false;
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + CONTACTS_TABLE_NAME, null);
        cursor.moveToFirst();
        int count = cursor.getInt(0);
        if(count > 0)
            hasRows = true;
        db.close();
        return hasRows;
    }
    public ArrayList<ContactListItems> getAllContacts() {
        ArrayList<ContactListItems> contactList = new ArrayList<>();
        hp = new HashMap();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from contacts", null);
        res.moveToFirst();
        while (!res.isAfterLast()) {
                ContactListItems contactListItems = new ContactListItems();

                contactListItems.setTitle(res.getString(res
                        .getColumnIndex("title")));
                contactListItems.setAmount(res.getFloat(res
                        .getColumnIndex("amount")));
                contactListItems.setDescription(res.getString(res
                        .getColumnIndex("description")));
                contactList.add( contactListItems);
                res.moveToNext();
            }
        res.close();
        return contactList;
    }
    public int getTotalOfAmount(){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c=db.rawQuery("SELECT SUM(amount) FROM " +CONTACTS_TABLE_NAME,null);
        c.moveToFirst();
        int i=c.getInt(0);
        c.close();
        return i;
    }
}

然而上面的代码并没有删除任何东西。我猜它的功能我还没有正确完成。有什么建议吗?

完整的DBHelper.java

obj.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                deleteDialog();
                return true;
            }
        });
    }

修改

android.database.sqlite.SQLiteException: near "=": syntax error (code 1): , while compiling: DELETE FROM contacts WHERE title=
            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
            at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
            at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
            at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
            at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
            at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
            at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
            at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
            at com.softtech.stevekamau.buyathome.DBHelper.removeSingleContact(DBHelper.java:157)
            at com.softtech.stevekamau.buyathome.MyCart$6.onClick(MyCart.java:140)
            at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

Logcat错误:

&#13;
&#13;
HasSpeed
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:18)

您可以使用SQL DELETE语句选择要删除的条目。 使用字符串值作为选择器时,请确保将值括在''

    /**
     * Remove a contact from database by title
     *
     * @param title to remove
     */
    public void removeSingleContact(String title) {
        //Open the database
        SQLiteDatabase database = this.getWritableDatabase();

        //Execute sql query to remove from database
        //NOTE: When removing by String in SQL, value must be enclosed with ''
        database.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + CONTACTS_COLUMN_TITLE + "= '" + title + "'");

        //Close the database
        database.close();
    }

然后,只要您想从数据库中删除条目,请使用以下命令:

DBHelper dbHelper = new DBHelper(context);
dbHelper.removeSingleContact("CONTACT_TO_REMOVE_HERE");

<强>更新 假设您的ListView数据集是包含ContactListItems的ArrayList,您可以为OnItemClickListener设置ListView并使用它来获取所选标题,然后将其删除。< / p>

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyCart.this);
        alertDialog.setCancelable(false);
        alertDialog.setMessage("Delete item?");
        alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String title;

                title = arrayList.get(position).getTitle();

                dbHelper.removeSingleContact(title);

                //Update your ArrayList
                arrayList = dbHelper.getAllContacts();

                //Notify your ListView adapter
                adapter.notifyDataSetChanged();

            }
        });
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        alertDialog.show();

    }

});

答案 1 :(得分:1)

我猜您的代码中的问题位于以下行:

myDb.deleteSingleContact(toString());

应该有标题作为参数。你没有传递任何东西。必须要从数据库中删除标题。如下所示:

myDb.deleteSingleContact(title.toString());

如果这不能解决您的问题,请告诉我。

<强>更新

要从数据库中删除记录,您必须定义一些信息,例如从数据库中删除要删除的记录。至少需要识别该记录的索引。 例如:你在数据库中有一些标题,如运动,喜悦,冒险,娱乐和动作。现在,如果要从数据库中删除操作记录。所以你需要做的是,你需要在上面的函数中将该标题名称作为参数传递。 (在你的情况下deleteSingleContact(&#34; Action&#34;))。因此,它会找到标题名称为&#34; Action&#34;它将从数据库中删除该记录。

希望你明白这一点。

如果您有任何疑问,请告诉我。

此致 Shreyash

答案 2 :(得分:1)

如果我在你身边,我会使用CursorAdapter的子类,CursorLoader,这样,您带到数据库的每个更改都会立即反映在ui上(您的{ {1}}),没有任何额外的代码行。为此,您必须在数据库中添加名为ListView_id查询的"_id INTEGER PRIMARY KEY AUTOINCREMENT"列。

假设您的create table数据集由ListView组成,当ContactListItems被调用时,您可以使用

检索您长按的对象
onItemLongClick

现在,如果您更改ContactListItems item = (ContactListItems) arg0.getItemAtPosition(arg2); 的签名,例如

deleteDialog
private void deleteDialog(final String title)

,您可以致电

onItemLongClick

您还必须更改

 @Override
 public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
     ContactListItems item = (ContactListItems) arg0.getItemAtPosition(arg2);
     deleteDialog(item.getTitle());
     return true;
 }

alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                myDb.deleteSingleContact(toString());
            }
});