【问题标题】:Accessing SQLite values from SimpleCursorAdapter从 SimpleCursorAdapter 访问 SQLite 值
【发布时间】:2011-08-16 21:17:42
【问题描述】:

我有一个名为“Nodes”的 SQLite 表,其中包含一组所有节点(每个节点都有多个属性)。

在一个活动中,我使用 SimpleCursorAdapter 的扩展来显示 Nodes 表的 子集,基于 SQL 查询,将光标传递给结果表(来自查询)。

{id_long, name_string, description_string, nodetype_enum_toString...}
    1, "home", "home_desc", "cool"
    2, "item1", "item1_desc", "warm"
    3, "item2", "item2_desc", "hot"
    4, "item3", "item3_desc", "warm"
    5, "item4", "item4_desc", "hot"

我想修改我的 ListActivity 中的每个列表项,使其根据项目是冷、暖还是热显示不同的颜色。我有一个小(空)视图,但它始终默认为白色(“其他”部分)。

public View getView(int position, View convertView, ViewGroup parent) {
    convertView = super.getView(position, convertView, parent);

    if (convertView == null) convertView = View.inflate(mContext, R.layout.viewstack_item, null);
    View nodetype_view = (View) convertView.findViewById(R.id.nodetype_view);

    mGenCursor_cur = mDataHelper_db.getAll();
    mGenCursor_cur.moveToPosition(position);

    Log.i("test", "node type key " + mGenCursor_cur.getColumnIndex(DataHelper.NODES_TYPE_KEY));
    String type_nt = mGenCursor_cur.getString(mGenCursor_cur.getColumnIndex(DataHelper.NODES_TYPE_KEY));
    String name_str = mGenCursor_cur.getString(mGenCursor_cur.getColumnIndex(DataHelper.NODES_NAME_KEY));
    Log.i("getView", title_str + "typeis " + type_nt + " at position " + position);

    if (prio_np.equals(NodePrio.HIGH.toString())) {
        Log.i("prio_np", "high red");
        prioView_view.setBackgroundColor(Color.RED);
    } else if (prio_np.equals(NodePrio.NORMAL.toString())) {
        Log.i("prio_np", "norm magenta");
        prioView_view.setBackgroundColor(Color.MAGENTA);
    } else {
        Log.i("prio_np", "else (low) white");
        prioView_view.setBackgroundColor(Color.WHITE);
    }

    mGenCursor_cur.close();
    bindView(convertView, mContext, getCursor());
    return(convertView);
}

我的问题是,虽然传递给 SimpleListAdapter 的光标将包含我想要的子集中相应节点的 _ID(我假设),但 getView中的 position 参数> 是子集的本地,所以我不能用 Nodes 表交叉引用它。我错过了一些简单的技巧吗?

一如既往,感谢您的帮助。

标记答案的评论 4 帮助我解决了这个问题: 将传递给 SimpleCursorAdapter 的光标存储为成员变量,然后使用 move to position 和 getLong:

mCursor_cur.moveToPosition(position);
long id = mCursor_cur.getLong(0);

其中position是getView()方法中的局部参数,0用于getLong,因为db_id是传给SimpleCursorAdapter的游标的第一列

【问题讨论】:

  • 不知道我是怎么把“一如既往的”加粗的,但我会留下它,因为它体现了我的感激之情:D

标签: android sqlite simplecursoradapter


【解决方案1】:

在 java 中 == 不应该用于字符串比较 string1.equals(string2) 是您正在寻找的 请参阅here 了解更多信息

【讨论】:

  • 谢谢,我总是把这两者混为一谈。
  • 不抱歉,字符串比较是问题的次要部分,我无论如何都会尝试,除了主要部分让我分心 - 从节点表中的行获取值,基于在光标上传递给 SimpleCursorAdapter
  • 我的错,我以为只有一个部分。但是对于第一部分,我记得我将列表(您的子集,但作为列表)保留为成员变量,以便我可以轻松引用它的位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多