2011-10-17 90 views
0

我正在使用它填充數據庫中的一些字段。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

如果你想讓你甚至可以在最終之前拋出一個catch –

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);