从列表中获取listItem数据

时间:2011-05-16 18:40:56

标签: java android listview

我讨厌由简单游标适配器创建的列表:

Cursor c = myDbHelper.rawQ(select);
    startManagingCursor(c);

    // the desired columns to be bound
    String[] columns = new String[] { "Books.BookTitle",
            "Publishers.Publisher" };
    // the XML defined views which the data will be bound to
    int[] to = new int[] { R.id.ISBN_entry, R.id.Title_entry };

    // Getting results into our listview
    try {
        SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
                R.layout.listlayout, c, columns, to);
        this.setListAdapter(mAdapter);
    } catch (Exception e) {

    }

列表涉及的布局是两个简单的文本视图。

我想做的是创建一个监听器

 @Override
protected void onListItemClick(ListView l, View v, int position, long id) { 

我失败的部分是检索特定条目(行)的BookTitle部分,以便重新查询数据库并使用AlertDialog.Builder呈现数据。

当我尝试做的时候:

 String selection = l.getItemAtPosition(position).toString(); 

我只是得到android.database.sqlite SQLiteCursor @ 44f99e80而且我对如何做到这一点感到困惑(我知道为什么它崩溃了就可以了;我想一想如何正确地完成它。

完整代码atm:

...
Cursor c = myDbHelper.rawQ(select);
    startManagingCursor(c);

    // the desired columns to be bound
    String[] columns = new String[] { "Books.BookTitle",
            "Publishers.Publisher" };
    // the XML defined views which the data will be bound to
    int[] to = new int[] { R.id.ISBN_entry, R.id.Title_entry };

    // Getting results into our listview
    try {
        SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
                R.layout.listlayout, c, columns, to);
        this.setListAdapter(mAdapter);
    } catch (Exception e) {

    }



}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
 // TODO Auto-generated method stub
 //super.onListItemClick(l, v, position, id);
 String selection = l.getItemAtPosition(position).toString();  
 new AlertDialog.Builder(v.getContext())
 .setTitle("Title")
 .setMessage(selection)
 .setPositiveButton(android.R.string.ok, null)
 .show();
} }

2 个答案:

答案 0 :(得分:6)

尝试这样的事情......

Cursor theCursor = ((SimpleCursorAdapter)((ListView)l).getAdapter()).getCursor();
String selection = theCursor.getString(theCursor.getColumnIndex("Books.BookTitle"));

答案 1 :(得分:1)

只需从光标中获取数据:

 l.getItemAtPosition(position).getString(0); // it might be 1

请参阅here