2015년 11월 8일 일요일

android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 에러 문제





안드로이드에서 DB 작업을 하다보면 다음과 같은 에러를 만날 때가 있다.

"android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of ..."

이 에러는 DB에서 SELECT한 결과를 Cursor로 받는데 이때 Cursor의 위치가 첫번째 항목 바로 앞(index가 -1인) 위치에 놓이게 된다.
이때 다음 명령을 실행하면 

cursor.getString(cursor.getColumnIndex("name"));

android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1과 같은 에러가 발생한다.
왜냐하면 cursor의 위치가 before the first entry이기 때문이다. 즉 cursor의 index가 첫 번째 데이터 바로 앞인 -1의 위치에 있기 때문이다.

이건 다음 둘 중 한 방법으로 처리 해야한다.

1) cursor.moveToFirst()를 cursor.getString() 이전에 실행해서 index가 -1인 (첫 번째 항목 바로 앞) 위치에서 첫 번째 항목으로 이동시킨 후
cursor.getString(cursor.getColumnIndex("name"));
과 같은 명령을 통해 원하는 데이터를 추출하면 된다.

2) while문을 이용해서 cursor.moveToNext()를 이용해서 하면 moveToFirst()를 안 해도 된다.
이때 movetToFirst()를 실행하면 맨 첫번째 데이터를 놓치고 넘어가게 된다.
while(cursor.moveToNext()) {...}를 하면 index -1에서 cursor.moveToNext()로 인해
첫 번째 데이터 위치로 index가 옮겨가게 되므로 굳이 moveToFirst()가 필요 없게 된다.

while(cursor.moveToNext()) {
name = cursor.getString(cursor.getColumnIndex("name"));
}

아래는 코드 조각이다.

DBHelper db_Helper = new DBHelper(mContext);
SQLiteDatabase db = db_Helper.getReadableDatabase();
String sql = "SELECT * FROM "+mContext.getString(R.string.memberTable) 
+" WHERE "+mContext.getString(R.string.pinNum)+"='"+pin_num+"';";
//A Cursor object, which is positioned before the first entry.
Cursor cursor = db.rawQuery(sql, null);
//cursor.moveToFirst(); 
if (cursor.getCount() > 0) {
while(cursor.moveToNext()) {
name = cursor.getString(cursor.getColumnIndex("name"));
}
}
db_Helper.close();

댓글 없음:

댓글 쓰기