2014-06-12 37 views
0

我在SQLite数据库中的表结构如下。 enter image description here我无法从光标对象获取数据

在我的SqliteOpenHelper类中,我写了下面的方法。

public Form getAllForms(){ 
    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor cursor = db.rawQuery("select * from "+FORM_TABLE, null); 
    int count = cursor.getCount(); 
    String formID = cursor.getString(0); 
    Form form = new Form(); 
    form.setId(formID); 
    cursor.close(); 
    db.close(); 
    return form; 
} 

我敢肯定有它的一些数据,因为我已经看过在调试模式下count,我看到的是实际存在于数据库行的数量。但是CursorIndexOutOfBoundException在cursor.getString(0)处显示。加上cursor.getInt(0)和cursor.getString(1)也不起作用。这可能是什么问题?

回答

3

您需要将光标移动到有效行。

有效行的索引从0到count-1。首先,光标将指向行索引-1,即紧挨在第一行之前的行索引。

通过所有行循环的典型方式是

if (cursor.moveToFirst()) { 
    do { 
     // now access cursor columns 
    } while (cursor.moveToNext()); 
} 
+0

'while(cursor.moveToNext()){...}'会更简单。 –

+0

@CL。它假定光标处于-1,这是一个有效的假设,但不是无处不在。 – laalto

+0

Yap ..,我只是忘记moveToFirst。非常感谢你laalto。 –

1

需要调用moveToFirst()去的第一行要求值之前:

if ((cursor!= null) && (cursor.getCount() > 0)) { 
       cursor.moveToFirst(); 
       while (cursor.isAfterLast() == false) { 
} 

所以您只需使用代码

public Form getAllForms(){ 
    Form form = new Form(); 
    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor cursor = db.rawQuery("select * from "+FORM_TABLE, null); 
    if ((cursor != null) && (cursor.getCount() > 0)) { 
       cursor.moveToFirst(); 
      while (cursor.isAfterLast() == false) { 
       String formID = cursor.getString(0); 
       form.setId(formID); 
     cursor.moveToNext(); 
     } 
    cursor.close(); 
    } 
    db.close(); 
    return form; 
} 
+0

不需要'null'检查。 while循环永远不会结束。 –

+0

@CL。它会检查游标是否位于最后一个结果之后,如果为false,它将从循环中存在 –

+0

但是在最后一行之后,游标永远不会移动。 –

1

试试这个

 try { 
     cursor.moveToFirst(); 

     for (int i = 0; i < cursor.getCount(); i++) { 

      Form form = new Form(); 
           form.setId(formID); 

      cursor.moveToNext(); 
     } 
        } finally { 
     // database.close(); 
     cursor.close(); 
     dbHelper.close(); 
    } 
+0

它的作品..!非常感谢... –