如何在上下文菜单中删除所选行?

时间:2012-07-07 21:25:49

标签: android sqlite android-contextmenu

当我从上下文菜单中选择删除菜单项时,我想删除sqlite db记录。 我创建了一个上下文菜单,它正在工作,但我无法删除数据库行。有没有办法删除记录?我该怎么办?

public void deleteItem(dbItem item) {
    SQLiteDatabase db = this.getWritableDatabase();

    db.delete(TABLE_ITEMS, items_id + " = ?",
        new String[] { String.valueOf(item.getID()) });
    db.close();
}

public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();

    int menuitemindex = item.getItemId();


    if(item.getItemId()==0)
    {
        //code for send text
    } 
    else if(item.getItemId()==1) // Delete menu item
    {
       //  db.deleteItem(item2);
    }
    return super.onContextItemSelected(item);    
 }

如何在上下文菜单部分使用 deleteItem()程序?

1 个答案:

答案 0 :(得分:0)

我在12天后找到了解决方案:)

public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();

    int menuitemindex = item.getItemId();


    if(menuitemindex == 0)
    {
        //code for send text
    } 
    else if(menuitemindex == 1)
    {           
        dbItem silinen = adapter.getItem(info.position);      
        adapter.remove(silinen);            
        adapter.notifyDataSetChanged();
        db.deleteItem(silinen, getApplicationContext());        
    }
    return super.onContextItemSelected(item);    
 }

删除程序:

public void deleteItem(dbItem item, Context context) {
    SQLiteDatabase db = this.getWritableDatabase();

    try {

      db.delete(TABLE_ITEMS, items_id + " = ?",
              new String[] { String.valueOf(item.getID())});

    } catch (Exception e) 
    {
      Log.e("insert",e.getMessage());
    }


    Toast.makeText(context, "Item succesfully deleted. Name: "+ item.getName(), Toast.LENGTH_LONG).show();

    db.close();        

}