2014-09-24 45 views
0

我與的Android SQLiteOpenHelper

java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: 
    java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it. 
    ... 

這裏應用程序崩潰是導致錯誤的方法:

public int getWeek(int yearAndWeek) throws CursorIndexOutOfBoundsException { 
    SQLiteDatabase db = this.getReadableDatabase(); 

    String selectQuery = "SELECT * FROM " + TABLE_WEEKS + " WHERE " 
      + KEY_WEEK + " = " + yearAndWeek; 

    Cursor c = db.rawQuery(selectQuery, null); 

    if (c.getCount() > 0) 
     c.moveToFirst(); 

    return c.getInt(c.getColumnIndex(KEY_WEEK_NUMBER)); 
} 

在此行return c.getInt(c.getColumnIndex(KEY_WEEK_NUMBER));出現的錯誤。請幫我解決這個錯誤。

+0

光標沒有任何價值迴歸。請檢查您的查詢,否則保持適當的驗證。 – SilentKiller 2014-09-24 11:00:39

+0

嘗試在logcat中打印'c.getCount()'如果它是0意味着沒有結果 – 2014-09-24 11:03:45

+0

這真的是導致異常的代碼嗎?很難看到你如何設法將光標移動到第0行,並使用此代碼獲取此異常。 – laalto 2014-09-24 11:04:53

回答

1

要保持從方法的正確答覆,您可以嘗試使用以下代碼。

public int getWeek(int yearAndWeek) throws CursorIndexOutOfBoundsException { 

    SQLiteDatabase db = this.getReadableDatabase(); 
    String selectQuery = "SELECT * FROM " + TABLE_WEEKS + " WHERE " + KEY_WEEK + " = " + yearAndWeek; 
    Cursor c = db.rawQuery(selectQuery, null); 

    if (c.getCount() > 0) { 
     c.moveToFirst(); 
     return c.getInt(c.getColumnIndex(KEY_WEEK_NUMBER)); 
    } 
    return -1;   
} 
+0

爲了安全起見,通常建議您在返回值之前關閉光標。 'c.close()' – erad 2014-09-24 11:06:46

+0

@SilentKiller,else {return -1;} - > return -1;它會更準確。 – AskQuestion 2014-09-24 11:20:22

+0

@AskQuestion根據您的建議更新了答案。 :) – SilentKiller 2014-09-24 11:23:56