Monday, May 2, 2011

[Android]android.database.CursorIndexOutOfBoundsException

這幾天在寫有關於Android資料庫SQLite的一些方法。在測試程式的過程中,一直出現ERROR/AndroidRuntime(865): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1這個例外訊息,檢查程式很多遍並沒有發現錯誤,查了一下exception的來源為Cursor.getString(index),我還特別確定了API中的寫法,寫法沒有錯啊,那為何會有exception產生呢?

仔細看了一下,原來Cursor.getString(index)當中的index變為-1了,難怪會有exception產生。

此時只要把Cursor的指標指為1就能夠正常運作。可加上以下判斷式:

if(cursor != null){
cursor.moveToFirst();
}

0 comments:

Post a Comment