0

我已经无法获得自动递增的ID

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; 

现在我试图让单个ID

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))); 

是什么问题?

+0

cursor.getColumnIndex(StudentDB.ST_ID)返回INTEGER,不要使用cursor.getString(),请使用cursor.getInt(); –

+0

这不是问题 – LynAs

回答

2

你没有在你的投影将其更改为添加您的ID:

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

如果您的投影中没有ID,则光标没有任何称为so的字段。

这样做:

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

@Sardor Dushamov,是正确的也是如此,如果ID是自动增量,使用getInt不GetString的。

0

请与投影的String [],你没有添加StudentDB.ST_ID