我创建了一个数据库,其中包含带有列(_id、title等)的表(类别)。我想从数据库中读取这些类别的数据,并将它们列在ListView
中。
这是我的代码:
public class MainActivity extends listActivity{
private ArrayAdapter arrayAdapter;
ArrayList results = new ArrayList();
ListView catlist;
Cursor cur;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
catlist = getListView();
int parentid = getIntent().getIntExtra("catid", 0);
openAndQueryDatabase(parentid);
displayCatListView();
}
private void displayCatListView() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
catlist.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
Toast.makeText(MainActivity.this,
"List View Clicked:" + position, Toast.LENGTH_LONG)
.show();
}
});
}
private void openAndQueryDatabase(int parentid) {
DataBaseHelper db = new DataBaseHelper(this);
SQLiteDatabase dbr = db.getReadableDatabase();
cur = dbr.rawQuery(
"SELECT _id, title, has_sub FROM categories where parent_id=?",
new String[] { String.valueOf(parentid) });
if (cur != null) {
while (cur.moveToNext()) {
int cat_id = cur.getInt(cur.getColumnIndex("_id"));
String cattitle = cur.getString(cur.getColumnIndex("title"));
int has_sub = cur.getInt(cur.getColumnIndex("has_sub"));
results.add(cat_id + cattitle + has_sub);
}
cur.close();
}
db.close();
}
}
- 我可以在ItemClick上获得项目的位置,但我想在ItemClicks上获得他们行的_id。我该怎么做
- 我是新手。我的代码中有错误吗
非常感谢。
使用CursorAdapter(http://developer.android.com/reference/android/widget/CursorAdapter.html)相反,当您使用ArrayAdapter时,它超出了内存分配,而且如果数据库发生更改,您也不会收到通知。
此外,在使用CursorAdapter的情况下,您将拥有
public void onItemClick(AdapterView<?> parent, View v, final int position, long id)
"id"参数将与表的_id字段一致
要获得整排,只需进行
adapter.getItem(int position)
而不是
int cat_id = cur.getInt(cur.getColumnIndex("_id"));
String cattitle = cur.getString(cur.getColumnIndex("title"));
int has_sub = cur.getInt(cur.getColumnIndex("has_sub"));
results.add(cat_id + cattitle + has_sub);
创建一个包含这些值的Category类,并使用参数化的ArrayList。类似的东西
class Category {
public int cat_id;
public String cattitle;
public int has_sub;
public Category(int cat_id, ...) {
// constructor logic here
}
}
和
results.add(new Category(cat_id, cattitle, has_sub));
这样,您就可以将onItemClickListener设置为:
catlist.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
Category clickedCategory = results.get(position);
int id = clickedCategory.cat_id;
// do something with id
}
});
您的ArrayList是ArrayAdapter的数据源,position
对应于其中单击的Category的索引。