Android SQLite获得CursorIndexOutOfBoundsException

时间:2012-05-29 02:21:21

标签: android database sqlite cursor

使用游标对Android数据库执行SQLite查询时遇到问题,如果我尝试使用getPage,我会得android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 错误,我对游标做错了吗?做一个cursor.getColumnCount()得到4是正确的,并且有一行,所以这不是问题,可能导致错误的原因是什么?提前致谢

public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 3;

// Database Name
private static final String DATABASE_NAME = "pagesManager";

// Pages table name
private static final String TABLE_PAGES = "pages";
// Pages Table Columns names
private static final String PAGES_KEY_ID = "id";
private static final String PAGES_KEY_NAME = "pageName";
private static final String PAGES_KEY_DATE = "lastDate";
private static final String PAGES_KEY_PAGE = "pageUrl";
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_PAGES_TABLE = "CREATE TABLE " + TABLE_PAGES + "("
            + PAGES_KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + PAGES_KEY_NAME + " TEXT,"+ PAGES_KEY_DATE + 
            " TEXT," + PAGES_KEY_PAGE + " TEXT" +")";
    db.execSQL(CREATE_PAGES_TABLE);
}

   public PageListItem getPage(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_PAGES, new String[] { PAGES_KEY_ID, PAGES_KEY_NAME, PAGES_KEY_DATE, PAGES_KEY_PAGE }, PAGES_KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        if(cursor.moveToFirst()) {
            System.out.println("Cursor no es nulo");
        }
    PageListItem page = new PageListItem(cursor.getString(1),cursor.getString(2), cursor.getString(3),Integer.parseInt(cursor.getString(0)));
    cursor.close();
    return page;
}
}

1 个答案:

答案 0 :(得分:1)

我使用了错误的ID,因此getPage()无法找到它。