2011-05-25 64 views
0

作爲Android java世界的初學者,我需要你的幫助。我遇到了着名的「CursorIndexOutOfBoundsException」問題。兩個遊標,ListView,CursorIndexOutOfBoundsException

我正在使用SQLite數據庫,我有兩個遊標,我從數據庫中獲取一些行。 我需要用第二個遊標(c2)的某些條件獲得一些以前的值,並將這些值放在ListView上。

代碼有一個例外: 「android.database.CursorIndexOutOfBoundsException:索引0請求,大小爲0」。

ListView看起來好,如果我只是忽略這個異常,但我想修復它。

我知道它與光標連接。我試圖檢查一些條件 - 它沒有幫助。也許如果你可以看看我的代碼,你會發現原因在哪裏。

代碼:

public void LoadLogGrid() 
{ 
    dbHelper=new DatabaseHelper(this); 
    try 
    { 

    int LogName = (int) spinLog.getSelectedItemId(); 
    Cursor c=dbHelper.getLogByLogID(LogName); 
    if (c != null) c.moveToFirst(); 
    int count = c.getCount(); 


    if (c.moveToFirst()){ 
     ArrayList<String> mArrayList = new ArrayList<String>(); 

    int i=0; 
    do { 

     int sVar1 = c.getInt(c.getColumnIndex("Var1")); 
     Long sId = (long) c.getInt(c.getColumnIndex("_id"));    

     Cursor c2=dbHelper.getPrevLogByLogID(LogName,sVar1);  
     c2.moveToFirst(); 

     if (c2!=null) { 
      String sPrevOdo = c2.getString(c2.getColumnIndex("Odo")); 
       mArrayList.add(sPrevOdo); 
       c2.close(); 
     } else { 
       //stopManagingCursor(c2); 
       //c2.close(); 
      Log.d("A:", "Something"); 
     } 


     String [] from=new String []{"Date","Col1","Col2","Col3"}; 
     int [] to=new int [] {R.id.logDate,R.id.logCol1,R.id.logCol2,R.id.logCol3,R.id.rowOpt2}; 
     SimpleCursorAdapter sca=new LogCursorAdapter(this,R.layout.loggridrow,c,from,to,mArrayList); 
     grid.setAdapter(sca); 
     registerForContextMenu(grid); 
     i++;  

    } while (c.moveToNext()); 

     c.close(); 

    dbHelper.close(); 
    } 

    } 
    catch(Exception ex) 
    { 
     AlertDialog.Builder b=new AlertDialog.Builder(this); 
     b.setMessage(ex.toString()); 
     b.show(); 
    } 

} 

查詢在第二個光標:

public Cursor getPrevLogByLogID(long LogID, long Var1) 
    { 
     SQLiteDatabase db=this.getReadableDatabase(); 
     String[] params=new String[]{String.valueOf(LogID),String.valueOf(Var1)}; 

     Cursor c2=db.rawQuery("SELECT LogID as _id, Col1 from Log WHERE Col2=? AND Col3<? AND Full=1 ORDER BY Odo DESC", params); 
     if (c2 != null) { c2.moveToFirst();} 
     return c2; 
    } 

回答

0

試着改變你的

do { 
    .... 
} while (c.moveToNext()); 

while (c.moveToNext()) { 
    .... 
} 

現在的樣子,無論如何它至少會運行一次循環。

+0

謝謝,但它沒有工作。改變這個後,我有更多的listView錯誤。目前,除了「異常」之外,看起來一切看起來都很像 @Karthik是的,但如何做到這一點。也許我做錯了,我想我嘗試了這個解決方案(也許我在做(可能是錯誤的) – adek 2011-05-26 07:21:46

0

您已將c2移動到c2.moveToFirst()的位置,之後您正在執行檢查過程,無論它是否爲null,並且我認爲光標應爲null,以便引發異常請嘗試將在將光標移動到第一個位置前檢查條件

+0

是的,但如何做到這一點。也許我做錯了,我想我試過這個解決方案(可能我做錯了什麼) – adek 2011-05-26 07:30:50

+0

這樣做if(c2!= null){String sPrevOdo = c2 .getString(c2.getColumnIndex(「Odo」)); mArrayList.add(sPrevOdo); c2.close();條件在你的情況是真的,並且mArrayList被填充? – Karthik 2011-05-26 08:59:22

相關問題