1

这是我的简单光标适配器的代码。

public class CursorList extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    DatabaseAdapter da = new DatabaseAdapter(this, "mydb.sqlite");

    da.open();
    Cursor cur = da.fetchAllRecords("Doctors", new String[]{"FirstName"});
    startManagingCursor(cur);

    cur.moveToFirst();
    do {
        Log.v("Info", cur.getString(cur.getColumnIndex("FirstName")));
    } while(cur.moveToNext());

    cur.moveToFirst();

    String[] from = new String[]{"FirstName"};
    int[] to = new int[]{R.id.row};

    SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.row_item, cur, from, to);

    setListAdapter(sca);
    }
}

数据记录在日志中正确显示,但代码到达时停止工作

SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.row_item, cur, from, to);

线。

我得到的错误是:

ERROR/AndroidRuntime(26746): Uncaught handler: thread main exiting due to uncaught exception
ERROR/AndroidRuntime(26746): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.arnab.cursorlist/com.arnab.cursorlist.CursorList}:
java.lang.IllegalArgumentException: column '_id' does not exist

我哪里错了?

为什么它会给出列“_id”不存在的错误?它是我们必须在表格中拥有的必要列吗?

编辑:

当我将光标相关代码放在 try catch 块中时,如下所示:

try {
        SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.row_item, cur, from, to);

        setListAdapter(sca);
    }
    catch(Exception E) {
        Log.v("Error", E.getMessage());
    }

我收到消息:

VERBOSE/Error(1026): column '_id' does not exist

@Rasel:这是fetchAllRecords方法

public Cursor fetchAllRecords(String table, String columns[]) {
    return mDb.query(table, columns, null, null, null, null, null);     
}
4

3 回答 3

2

为什么它会给出列“_id”不存在的错误?它是我们必须在表格中拥有的必要列吗?

是的,如果您想在游标适配器中使用您的数据库信息。适配器将其用于内部目的。您的表必须有一个“_id”列,并且您必须在查询中选择它(所以它在Cursor结果集中)。您不必在ListView.

为后代修订

您可以将自己的“id”列作为“_id”,而不是实际添加“_id”列,SELECT它的工作原理是一样的。

于 2011-07-12T06:10:18.007 回答
0

在 try catch 块中编写与光标相关的代码。您的问题将得到解决。检查创建表时您键入了不同的列而不是“_id”

于 2011-07-12T06:03:51.713 回答
0

您需要在投影中包含表 _id。列表游标适配器需要 _id 来跟踪行。您不必在任何地方实际显示或使用它,但光标需要包含该列。在每个 android 表中,一个名为 _id 的主键列也是必需的。

于 2011-07-12T06:12:14.750 回答