【问题标题】:How to get data from Cursor into ContextMenu如何从光标获取数据到 ContextMenu
【发布时间】:2012-07-26 18:17:23
【问题描述】:

我想获取光标的当前记录,而不仅仅是 ID,以便我可以操作上下文菜单。

我看到了这个例子here,它向你展示了如何获取 ID:

 @Override
  public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case DELETE_ID:
        AdapterView.AdapterContextMenuInfo info=
          (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();

        delete(info.id);
        return(true);
    }

    return(super.onOptionsItemSelected(item));
  }

这很棒,因为它允许我获得单击的上下文菜单的适当 SQLite 数据库 ID,这将允许我编写一个函数来进行查找。但我肯定可以重用当前光标吗?

我试过这样做:

Cursor c = (Cursor) this.getListAdapter().getItem((int) info.id);
String itemPriority = c.getInt(1);  
Log.v(TAG, "Current item:" + itemPriority);

但光标行似乎只返回数据库的架构,而不是我所追求的记录。

有人可以解释一下吗?

编辑:感谢@azgolfer,我找到了解决方案。我使用 fillData() 方法来填充适配器。通常这是在没有变量的情况下声明的。我不得不用一个字段变量重新定义这个方法。使光标适配器在 onContextItemSelected 中可见的代码的相关部分在这里:

private void fillData() {
    Cursor itemsCursor = mDbHelper.fetchAllItemsFilter(mListId, mStatusFilter);
    startManagingCursor(itemsCursor);
    mItemAdaptor = new ItemAdapter(this, itemsCursor);
    this.setListAdapter(mItemAdaptor);      
}

【问题讨论】:

  • 重用是什么意思? c.getInt(1) 正在获取该游标行的索引 1。因此,只需从该游标行的其他索引中获取记录,例如c.getString(2)。除非你正在尝试做其他事情。
  • 对不起,我猜工作重用应该是“使用”。重点是游标不返回数据,只返回模式。
  • 您能打印一下itemPriority 显示的内容吗?

标签: android sqlite contextmenu simplecursoradapter


【解决方案1】:

您正在使用 CursorAdapter 来显示您的列表项,对吗?然后,您已经可以通过在 CursorAdapter 本身上调用 getCursor() 来访问光标。要从光标中检索正确的记录,您只需要获取用户按下的项目的位置,然后将光标移动到该位置并检索您的数据。

首先,确定用户按下的位置:

AdapterView.AdapterContextMenuInfo info=
      (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int itemPosition = info.position; 

然后将光标移动到所需位置并检索记录:

Cursor cursor = (Your cursorAdapter).getCursor();
cursor.moveToPosition(itemPosition);
String itemPriority = cursor.getInt(1);  
Log.v(TAG, "Current item:" + itemPriority);

【讨论】:

  • 您的回答帮助我找到了解决方案。问题是我不知道您可以将适配器声明为字段变量。我已经更新了我原来的问题,包括我定义适配器的位置。
猜你喜欢
  • 2015-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多