Android从列表视图中获取数据

时间:2017-01-01 17:52:54

标签: android sqlite listview

我目前正在编写一个带有listview的APP,其中填充了来自SQLite表的数据,如下所示:

public void printDatabase(){
    Cursor c = handler.getAllRows();
    String[] fieldNames = new String[] {DBHandler.COLUMN_WORKER_ID, DBHandler.COLUMN_WORKER_NAME, DBHandler.COLUMN_WORKER_SURNAME, DBHandler.COLUMN_WORKER_COST};
    int[] toView = new int[] {R.id.item_worker_id, R.id.item_worker_name, R.id.item_worker_surname, R.id.item_worker_cost};
    SimpleCursorAdapter cAdapter;
    cAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.worker_items, c, fieldNames, toView, 0);
    list = (ListView) findViewById(R.id.worker_listView);
    list.setAdapter(cAdapter);
}

现在,我想通过点击该项来获取项目列表视图中的数据。我到处搜索,找到了解决方案,发现了这个:

class ItemListener implements AdapterView.OnItemClickListener{

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Object o = list.getItemAtPosition(i);
        String s = list.toString();
    }
}

但我得到的是对用于填充列表视图的光标的引用。从listview获取数据需要什么?

3 个答案:

答案 0 :(得分:2)

你已经到了解决方案的一半了。

Cursor itemCursor = (Cursor) list.getItemAtPosition(i);

这将返回指向所单击行的光标。您可以从中获取数据:

class ItemListener implements AdapterView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Cursor itemCursor = (Cursor) list.getItemAtPosition(i);

        String workerId = itemCursor.getString(itemCursor.getColumnIndex(DBHandler. COLUMN_WORKER_ID));
        String workerName = itemCursor.getString(itemCursor.getColumnIndex(DBHandler.COLUMN_WORKER_NAME));
        String workerSurname = itemCursor.getString(itemCursor.getColumnIndex(DBHandler.COLUMN_WORKER_SURNAME));
        String workerCost = itemCursor.getString(itemCursor.getColumnIndex(DBHandler.COLUMN_WORKER_COST));
    }
}

答案 1 :(得分:1)

使光标全局化;

Cursor cursor ;

在你的OnItemClick

class ItemListener implements AdapterView.OnItemClickListener{

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
     cursor.moveToPosition(position);
     String Id = cursor.getString(itemCursor.getColumnIndex(DBHandler. COLUMN_WORKER_ID));
 }

}

答案 2 :(得分:0)

试试这个:

class ItemListener implements AdapterView.OnItemClickListener{

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    TextView textView = (TextView) view.findViewById(R.id.list_content);
        String text = textView.getText().toString(); 
        //Log.d("Choosen: " + text);
}}