如何通过上下文菜单从SQLite数据库中删除项目?

时间:2019-06-29 09:35:02

标签: java android sqlite listview contextmenu

请帮助我理解。我有一个应用程序,其中将项目添加到数据库,然后将其显示在ListView上。几乎所有的方法都可以正常工作,但是当我通过快捷菜单删除项目时,顶部的第一项将被删除。不管我选择哪个项目。

@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, view, menuInfo);

    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.menu, menu);
}

@Override
public boolean onContextItemSelected(MenuItem menuItem) {
    switch (menuItem.getItemId()) {
        case R.id.delete_menu_item:
            String itm_ps = itemView.getItemAtPosition(itemPos).toString();
            ToDoDB.deleteData(itm_ps);
            mAdapter.remove(itm_ps);
            return true;

        case R.id.quit_menu_item:
            finish();
            return true;

        default:
            return super.onContextItemSelected(menuItem);
    }
}

和SQL查询代码:

public int deleteData(String value) {
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.query(TABLE_NAME,null, null, null, null, null, null);
    if (cursor.moveToFirst()) {
       delete_result = database.delete(TABLE_NAME, KEY_ID + "=?", new String[]{value});
       database.close();
    }
    return delete_result;
}

public Cursor viewData() {
    SQLiteDatabase database = this.getReadableDatabase();
    String query = "SELECT * FROM " + TABLE_NAME;
    Cursor cursor = database.rawQuery(query, null);

    return cursor;
}

1 个答案:

答案 0 :(得分:0)

在您的sql数据库中尝试一下。

public void delete(String time) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME, KEY_ID + " = ?", new String[]{time});
        db.close();
    }

也这样称呼它:

@Override
public boolean onContextItemSelected(MenuItem menuItem){
    switch(menuItem.getItemId()) {
        case R.id.delete_menu_item:

            AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
            String key = ((TextView) info.targetView).getText().toString();
            db.delete(String.valueOf(key));
            mAdapter.notifyDataSetChanged();
//  Load items to the database once more like you would do at startup of the application.
            return true;
   }
}