异常:游标索引超出范围

时间:2013-04-15 05:17:12

标签: android database eclipse

以下是活动中的代码:

//query
final dbhelper helper = new dbhelper(this);
Cursor c = helper.query();
boolean exist =false;
if(c != null && c.moveToFirst()){
Log.d("atestdbChar1no",String.valueOf(c.getCount()));   
int i=0;
while(c.isAfterLast()){
Log.d("atestdb1",String.valueOf(i++));
Log.d("atestdb2",String.valueOf(c.getInt(0)));
Log.d("atestdb3",c.getString(1));
Log.d("atestdb4",c.getString(2));
c.moveToNext(); 
}

//insert
      ContentValues values = new ContentValues();
      if(!finWords.equals("null")){
      if(finWords.length()>index){
      String selectWord = finWords.substring(index, index+1);
       values.put("character", finChar);
      values.put("word", selectWord);
      helper.insert(values);

以下是SQLiteOpenHelper中的代码:

public void insert(ContentValues values) {
    SQLiteDatabase db = getWritableDatabase();
    db.insert(TBL_NAME, null, values);
    Log.d("test", "dbinsert");
    db.close();
}

public Cursor query() {
    SQLiteDatabase db = getWritableDatabase();
    Cursor c = db.query(TBL_NAME, null, null, null, null, null, null);
    Log.d("test", "dbquery");
    return c;
}

我可以将数据插入数据库 但我无法查询它们 logcat说光标索引超出范围 并输出一些数据,例如只输出id为1,2,4,7的输出,然后强制关闭App 但我已经插入了14个数据 我的代码错了什么?

1 个答案:

答案 0 :(得分:1)

你忘了否定c.isAfterlast(),除非你传回null,否则你不必检查空游标。

if(c.moveToFirst()){
Log.d("atestdbChar1no",String.valueOf(c.getCount()));   
int i=0;
while(!c.isAfterLast()){
Log.d("atestdb1",String.valueOf(i++));
Log.d("atestdb2",String.valueOf(c.getInt(0)));
Log.d("atestdb3",c.getString(1));
Log.d("atestdb4",c.getString(2));
c.moveToNext(); 
}