2011-10-17 2 views
0

저는 이것을 사용하여 데이터베이스의 일부 필드를 채 웁니다. activity를 다시 시작할 때 indexOutOfBounds

private void populateField() { 

if(mRowId != null){ 

    Cursor Message = mDbHelper.fetchScheduledTask(mRowId); 
    startManagingCursor(Message); 
    Log.e("ROWID", mRowId.toString()); 
    String commaText = (Message.getString(Message.getColumnIndexOrThrow(SmsDbAdapter.KEY_NUMBERS))); 
    numbers.setText(commaText); 

은 활동 후 일시 정지 때 오류

10-17 11:15:13.123: ERROR/AndroidRuntime(15432): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 

그것은이 코드 라인에 포인트를 얻을 다시 시작했다.

String commaText = (Message.getString(TextMessage.getColumnIndexOrThrow(SmsDbAdapter.KEY_NUMBERS))); 

어떻게이 오류를 제거하거나 방어 할 수 있습니까?

답변

3

커서를 사용하기 전에 커서가 비어 있는지 확인해야합니다.

if (Message.moveToFirst()) { 
    String commaText = (Message.getString(Message.getColumnIndexOrThrow(SmsDbAdapter.KEY_NUMBERS))); 
    numbers.setText(commaText); 
    // Whatever else you want to do with the cursor 
} 

커서에 항목이 없으면 moveToFirst()가 false를 반환합니다. !

+0

고정 작은 오타 제안 - 당신이 '하지'(확인되었다 Message.moveToFirst을()) ... 제거! ... 커서가 첫 번째 위치로 이동할 수 있으면 유효한 행이 있습니다. – SBerg413

+0

죄송합니다. 편집 해 주셔서 감사합니다. – goto10

1
private void populateField() { 

    if(mRowId != null){ 

     Cursor Message = mDbHelper.fetchScheduledTask(mRowId); 
     try{ 
      if(Message != null && Message.moveToNext()){ 
       startManagingCursor(Message); 
       Log.e("ROWID", mRowId.toString()); 
       String commaText = Message.getString(Message.getColumnIndexOrThrow(SmsDbAdapter.KEY_NUMBERS))); 
       numbers.setText(commaText); 
      } 
     }finally{ 
      if(Message != null){ 
       try{ 
        Message.close(); 
       } catch(Exception e){} 
      } 
     } 
    } 
} 
+0

당신이 마침내 잡을 수 있기를 원한다면 :) –

1

을 사용하면 coder_for_life 같은 IFS으로 테스트 할하지 않는 경우 try/catch 블록이

private void populateField() { 

if(mRowId != null){ 
    Cursor Message = mDbHelper.fetchScheduledTask(mRowId); 
    startManagingCursor(Message); 
    Log.e("ROWID", mRowId.toString()); 
    try{ 
     String commaText = (Message.getString(Message.getColumnIndexOrThrow(SmsDbAdapter.KEY_NUMBERS))); 
    }catch (CursorIndexOutOfBoundsException e){ 
     //do something to handle the error 
    } 
    numbers.setText(commaText); 
관련 문제