无法获得自动增加的ID

时间:2013-10-02 07:22:02

标签: android sqlite android-contentprovider android-contentresolver

我有以下数据库配置

public static final String ST_ID = "s_id";  
public static final String ST_NAME = "s_name";
public static final String ST_COURSE = "s_course";
public static final String DBCREATE_STUDENTDB = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME+" ("                  
                + "s_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "s_name VARCHAR, "
                + "s_course VARCHAR);";
        public static final int VERSION = 1;

现在我想获得个人身份

final ContentResolver resolver = getContentResolver();
final String[] projection = { StudentDB.ST_NAME, StudentDB.ST_COURSE };
Cursor cursor = resolver.query(StudentDataProvider.studentTableUri, projection, null,  null, null);

if (cursor.moveToFirst()) {
    do {

        Log.wtf("ID", ""+cursor.getString(cursor.getColumnIndex(StudentDB.ST_ID)));

    } while (cursor.moveToNext());
}

我收到了这个错误。

10-02 07:14:29.788: E/AndroidRuntime(2252): java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

但是以下代码适用于其他列

Log.wtf("List", ""+cursor.getString(cursor.getColumnIndex(StudentDB.ST_COURSE)));

问题是什么?

3 个答案:

答案 0 :(得分:2)

final String[] projection = { StudentDB.ST_NAME, StudentDB.ST_COURSE };

如果投影中没有ID,则光标没有任何名称。

这样做:

final String[] projection = { StudentDB.ST_ID, StudentDB.ST_NAME, StudentDB.ST_COURSE };

@Sardor Dushamov,也是对的,如果ID是自动增量,请使用getInt而不是getString。

答案 1 :(得分:2)

您未在投影中添加ID,请将其更改为:

final String[] projection = { StudentDB.ST_NAME, StudentDB.ST_COURSE,StudentDB.ST_ID};

答案 2 :(得分:0)

查看您的投影字符串[],您没有添加StudentDB.ST_ID