Android - 获取ListView项的ID [特例]

时间:2011-07-11 13:15:20

标签: android sqlite android-listview simplecursoradapter android-cursor

在我的DB类中有一个返回Cursor的方法。游标将包含来自不同表的数据:

public Cursor fetchFavTitles() {
    return myDataBase.rawQuery("SELECT rowid as _id, title, fav FROM table1 " +
                                "WHERE fav = 1 UNION ALL " +
            "SELECT rowid as _id, title, fav FROM table2 WHERE fav = 1 UNION ALL " +
            "SELECT rowid as _id, title, fav FROM table3 WHERE fav = 1 UNION ALL " +
            "SELECT rowid as _id, title, fav FROM table4 WHERE fav = 1 UNION ALL " +
            "SELECT rowid as _id, title, fav FROM table5 WHERE fav = 1 UNION ALL " +
            "SELECT rowid as _id, title, fav FROM table6 WHERE fav = 1", null);

}

然后,我使用SimpleCursorAdapter caCursor附加到ListView lv

Cursor cursor = myDbHelper.fetchTitles(c);
String[] columns = {cursor.getColumnName(1)}; 
int[] columnsLayouts = {R.id.item_title};
ca = new SimpleCursorAdapter(this.getBaseContext(), R.layout.items_layout, cursor,columns , columnsLayouts);
lv = getListView();
lv.setAdapter(ca);

现在,如果我在ListView中选择任何项目,我想要引用该项目ID。 我希望id从项目所属的表中检索其他信息。并在其他活动MsgView

中检索它

我试过了:

  • 引用项目点击时传递的ID

  • 使用intent传递该值,以便其他活动将使用此传递的值检索所需的数据。

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            Intent i = new Intent(view.getContext(), MsgView.class);
                i.putExtra("id", (int) id); //
                startActivity(i);
        }
        });
    

然而,这不起作用。似乎我正在使用的id不是该项目的ID! 任何解决方案或想法?

5 个答案:

答案 0 :(得分:3)

在onItemClick方法中试试这个......

final SimpleCursorAdapter simpleCursorAdapter = (SimpleCursorAdapter) parent.getAdapter();
final Cursor cursor = simpleCursorAdapter .getCursor();

final int idColIndex = cursor.getColumnIndex(KEY_ROWID); //_id column of your table
final int rowId = cursor.getInt(idColIndex);

在我的一个项目中使用的是link,请参阅第41行。希望这有帮助。

编辑:

解决 的。见评论。

答案 1 :(得分:2)

您希望position参数不是id

请参阅onItemClick的文档:

public abstract void onItemClick (AdapterView<?> parent, View view, int position, long id) 

从以下版本开始:当单击此AdapterView中的项目时,将调用API Level 1 Callback方法。

如果需要访问与所选项目相关联的数据,实施者可以调用getItemAtPosition(position)。

参数

  

parent:发生单击的AdapterView。

     

view:被点击的AdapterView中的视图(这将是适配器提供的视图)

     

position:适配器中视图的位置。

     

id:单击的项目的行ID。

答案 2 :(得分:0)

您可以在MsgView类中创建用于存储ID的静态数据成员,或者可以向类发送延迟消息,确保在消息到达之前加载并启动活动

答案 3 :(得分:0)

您可以使用View.setTag()View.getTag()方法在视图中存储任何数据。有时我利用它来“标记”一个Intent对象到ListView中的每一行。每当我需要查找行的数据时,我只需使用getTag()

返回Intent

答案 4 :(得分:0)

我找到了解决问题的方法。

虽然它不是专业的解决方案,但它是我现在唯一的解决方案。我在每个表中添加了一个名为tableNumber的新列,以便每个表都有不同的数字。然后,我可以根据该数字来区分项目。

感谢您的回答。特别感谢@gopal