2014-06-12 38 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

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