Android 如何从表中获取_id字段并将其放入ListView
我有点糊涂了Android 如何从表中获取_id字段并将其放入ListView,android,android-listview,android-adapter,Android,Android Listview,Android Adapter,我有点糊涂了 SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.bugs_list_item, itemCursor, new String[] {db.KEY_ROWID, db.BUGS_DATE, db.BUGS_DESCRIPTION}, new int[] {R.id.bug_id, R.id.bug_date, R.id.bug_desc
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.bugs_list_item, itemCursor,
new String[] {db.KEY_ROWID, db.BUGS_DATE, db.BUGS_DESCRIPTION},
new int[] {R.id.bug_id, R.id.bug_date, R.id.bug_description});
这基本上显示了一个带有日期和描述但没有id的ListView(我只是用空格代替id)_id字段是主键,它是一个整数
看看它在img上的样子
XML文件:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1"
>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/bug_id"
android:layout_width="5dip"
android:layout_height="wrap_content"
android:padding="3dip"
>
</TextView>
<TextView
android:id="@+id/bug_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:gravity="right"
>
</TextView>
<TextView
android:id="@+id/bug_description"
android:layout_width="180dip"
android:layout_height="wrap_content"
android:padding="3dip"
android:gravity="right"
>
</TextView>
</TableRow>
</TableLayout>
非常重要的是,您的“id字段”必须有名称“\u id”,否则它可能无法工作。列表视图行的XML是什么样子的?你把身份证设置正确了吗 编辑:
由于您的XML文件似乎设置正确,我现在认为您的问题在于其他方面。可能是bug_id字段的数据未正确存储或从数据库中检索 这来自android文档:
'确保为记录的id包含一个名为“_id”(带有常量_id)的整数列。无论是否有其他字段(如URL)在所有记录中也是唯一的,都应该有此字段。如果使用的是SQLite数据库,_ID字段应为以下类型: 整数主键自动递增' 尝试更改create table SQL,为bug_id字段提供如下别名:
bug_id as _id integer primary key autoincrement,
与之相反:
bug_id integer primary key autoincrement,
只需从该代码中获取ID并将该代码粘贴到Database.java文件-
String[] return_result()
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(tableName, new String[] { "_id", "date", "description"},null, null, null, null, null);
String[] result = new String[cursor.getCount()];
int i = 0;
if(cursor.moveToFirst())
{
do
{
result[i]= cursor.getString(cursor.getColumnIndex("_id"));
i++;
}while(cursor.moveToNext());
}
if (cursor!=null && !cursor.isClosed())
{
cursor.close();
db.close();
}
return result;
}
在您的主java文件中,可以这样使用-
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.bugs_list_item, itemCursor,
new String[] {db.return_result(), db.BUGS_DATE, db.BUGS_DESCRIPTION},
new int[] {R.id.bug_id, R.id.bug_date, R.id.bug_description});
发现问题:
android:layout_width="5dip"
android:padding="3dip"
版面宽度只有5px,当我用3px填充文本时,它可能会消失在另一个版面下面。。。geez有点不知道为什么它很重要,我一直在关注示例,但是是的,它确实有它,所以你想用listview na显示项目id?bug_id作为_IDInteger主键autoincrement+sqlite似乎不太喜欢它,它说这是因为“as”甚至试图创建额外的列bug_id,我制作了主键,但它也没有被列入名单
android:layout_width="5dip"
android:padding="3dip"