我正在尝试获取ListView成员的数据库ID,以便我可以将其传递给新活动,但SimpleCursorAdapter的.getItemId(position)方法返回null,而不是数据库中的_id。我的理解是,它应该返回光标抓住的_id字段,但它对我来说不起作用。会喜欢一些建议
DatabaseHelper helper = new DatabaseHelper(this);
database = helper.getWritableDatabase();
Cursor data = database.query("myDb", fields, null, null, null, null, null);
dataSource = new SimpleCursorAdapter(this, R.layout.row, data, fields, new int[] {R.id.idText, R.id.castName, R.id.castDescription});
data.moveToFirst();
final ListView view = getListView();
view.setHeaderDividersEnabled(true);
view.addHeaderView(getLayoutInflater().inflate(R.layout.row, null));
setListAdapter(dataSource);
database.close();
view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// Prepare intent
Intent newActivity = new Intent(getApplicationContext(), ItemIdTester.class);
newActivity.putExtra("itemId",dataSource.getItemId(position));
// start activity
startActivity(newActivity);
}
});
答案 0 :(得分:1)
由于
添加了标头,适配器返回nullview.setHeaderDividersEnabled(true);
view.addHeaderView(getLayoutInflater().inflate(R.layout.row, null));
我也开始直接从光标获取数据。这是修复问题的完整onItemClickListener
view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Cursor cursor = (Cursor) dataSource.getItem(position-1);
Long itemId = cursor.getLong(0);
// Prepare intent
Intent newActivity = new Intent(getApplicationContext(), CastrRecorder.class);
newActivity.putExtra("itemId",itemId.toString());
// start activity
startActivity(newActivity);
}
});