为什么它无法读取ListView?

时间:2012-01-30 13:53:04

标签: android string sqlite listview

当我点击ListView项目时,我收到以下消息: 如何读出项目并将项目名称设为字符串?

android.database.sqlite.SQLiteCursor@40706330

public void onListItemClick(
ListView parent, View v,
int position, long id)
{   
    Object o = this.getListAdapter().getItem(position);
    String keyword = o.toString();

    Toast.makeText(this, keyword, Toast.LENGTH_SHORT).show();

} 

这样我可以从项目中读取位置:

    public void onListItemClick(
ListView parent, View v,
int position, long id)
{   
    open_database_rw();

    Object itemId = this.getListAdapter().getItemId(position);
    String item = itemId.toString();

    Toast.makeText(this, item, Toast.LENGTH_SHORT).show();

}  

现在我想把所选数据读出来祝酒。我试过这种方式,但它不起作用:

public void onListItemClick(
ListView parent, View v,
int position, long id)
{   
    open_database_rw();

    Cursor cursor = db.query("tbl_homework", new String[] {"hw"}, 
            "_id = 1", null, null, null, null);

    int column = cursor.getColumnIndex("hw");
    String item = cursor.getString(column);

    Toast.makeText(this, item, Toast.LENGTH_SHORT).show();

} 

ERRORMESSAGE: android.database.CursorIndexOutOfBoundsException:请求索引-1,大小为1

问题已经解决了!我不得不将光标移到第一位 cursor.moveToFirst();

完整的工作代码:

public void onListItemClick(
ListView parent, View v,
int position, long id)
{   
    open_database_rw();

    Object itemId = this.getListAdapter().getItemId(position);
    String item = itemId.toString();

    Cursor cursor = db.query("tbl_homework", new String[] {"hw"}, 
            "_id =" + item, null, null, null, null);

    cursor.moveToFirst();
    int column = cursor.getColumnIndex("hw");
    String hw = cursor.getString(column);
    Toast.makeText(this, hw, Toast.LENGTH_SHORT).show();
}  

3 个答案:

答案 0 :(得分:2)

如果你不知道你在ListView中插入了什么,那么如何指定要读取的列?

无论如何,你可以试试这个:

public void onListItemClick(ListView parent, View v,int position, long id)
{   
    Cursor c = (Cursor) this.getListAdapter().getItem(position);

    // if 0 doesn't work then try 1, 2, 3
    // and so on (depending on your columns length)
    String keyword = c.getString(0);

    Toast.makeText(this, keyword, Toast.LENGTH_SHORT).show();
}

答案 1 :(得分:1)

调用getItem()会返回与Adapter中指定位置相关联的“项目”。如果是CursorAdaptergetItem()会返回Cursor,请设置为正确的位置。如果您希望从Cursor中获取数据,请致电getString()getInt()或任何其他列getter on the Cursor interface

答案 2 :(得分:0)

以下代码将解决问题:

public void onListItemClick(
ListView parent, View v,
int position, long id)
{   
    open_database_rw();

    Object itemId = this.getListAdapter().getItemId(position);
    String item = itemId.toString();

    Cursor cursor = db.query("tbl_homework", new String[] {"hw"}, 
            "_id =" + item, null, null, null, null);

    cursor.moveToFirst();
    int column = cursor.getColumnIndex("hw");
    String hw = cursor.getString(column);
    Toast.makeText(this, hw, Toast.LENGTH_SHORT).show();
}  

必须将光标移动到第一位。