2011-09-05 74 views
0

我已经看到了几个解决方案,但非严格足够与我的示例相关。从ContextMenu项目获取价值(涉及数据库)

我从xml文件创建contextmenu并从数据库中填充ListView。

这里是我的上下文菜单的xml文件:

<?xml version="1.0" encoding="utf-8"?> 
<menu 
    xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:title="Revalue" android:id="@+id/expense_revalue"></item> 
    <item android:title="Delete" android:id="@+id/expense_delete"></item> 

</menu> 

而且一个ListView命令datafill方法:

private void fillData() {  

     ArrayList<HashMap<String, String>> myList = new ArrayList<HashMap<String, String>>(); 
     HashMap<String, String> map = new HashMap<String, String>(); 

     Cursor itemCursor = db.fetchAllItemsInExpenses();  

     if (itemCursor.moveToFirst()){ 
      do{ 
       String sCategory = itemCursor.getString(itemCursor.getColumnIndex(db.EXPENSE_CATEGORY)); 
       String sDate = itemCursor.getString(itemCursor.getColumnIndex(db.EXPENSE_DATE)); 
       String sValue = itemCursor.getString(itemCursor.getColumnIndex(db.EXPENSE_VALUE)); 

       map = new HashMap<String, String>(); 
       map.put(db.EXPENSE_CATEGORY, sCategory); 
       map.put(db.EXPENSE_DATE, sDate); 
       map.put(db.EXPENSE_VALUE, sValue); 
       myList.add(map);     

      }while (itemCursor.moveToNext());   
     } 

     SimpleAdapter expensesList = new SimpleAdapter(this, myList, R.layout.expenses_list_item, 
       new String[] {db.EXPENSE_CATEGORY, db.EXPENSE_DATE, db.EXPENSE_VALUE}, 
       new int[] {R.id.expense_category, R.id.expense_date, R.id.expense_value}); 
     setListAdapter(expensesList); 
     //list.setAdapter(expensesList); 


     //this.setListAdapter(new ArrayAdapter<String>(this, R.layout.expenses_list_category, category)); 

    } 

我想要做的是正确的删除方法(但我失败了,因为我不能得到id匹配数据库,所以我可以删除一条记录)

我试过这样的事情,但ID不匹配(这是什么值我是这样geting?)

@Override 
public boolean onContextItemSelected(MenuItem item) { 
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); 
    switch (item.getItemId()) { 
    case R.id.expense_revalue: 
     return true; 
    case R.id.expense_delete:   
     db.deleteItem(db.TABLE_EXPENSES, info.id); 
     fillData(); 
     return true; 
    }  
    return super.onContextItemSelected(item); 
} 

public boolean deleteItem(String tableName,long rowId) { 
    return SQLDb.delete(tableName, KEY_ROWID + "=" + rowId, null)>0; 
} 

所有我需要的是ID数据库相匹配的ID ......我想

回答

0

第1步:使用CursorAdapter(也许是SimpleCursorAdapter),而不是SimpleAdapter

第2步:没有步骤#2 - 您现有的info.id逻辑应该工作,那么,假设Cursor中有

Here is a sample project展示填充从数据库中ListView和使用上下文菜单中选择您_id列。

+0

我不能使用SimpleCursorAdapter(你是正确的info.id解决方案然后)。这是因为我需要格式化一些数据,然后将它们放入ListView中,SimpleCursorAdapter将数据直接从表传递给ListView:/ –

+0

也许它适用于我将_id包含在CursorAdapter中的查询?嗯,现在要检查它 –

+0

@ user928611:你仍然可以使用'SimpleCursorAdapter'。重写'bindView()'或使用'ViewBinder'。我还没有用'SimpleAdapter'试过'_id',所以我不知道它是否被传递。 – CommonsWare