2013-06-04 160 views
0

有人嗎?請幫我弄清楚這一點。我得到一個android.database.cursorindexoutofboundsexception錯誤,我不知道爲什麼。我敢肯定,我的名字是正確的,但我仍然知道。我想要做的只是獲取給定公司名稱的公司代碼。如何解決android.database.cursorindexoutofboundsexception錯誤?

這裏我的代碼我DatabaseAdapter

public Cursor getCompanyCode(String company) 
{ 
    Cursor c = dbSqlite.query(Constants.DATABASE_TABLE_COMPANY, 
      new String[] { Constants.DATABASE_COLUMN_ID, 
          Constants.COMPANY_CODE,Constants.COMPANY_NAME}, 
      Constants.COMPANY_CODE+" = ?", 
      new String[]{company}, null, null, null); 

    if (c != null) 
    { 
     c.moveToFirst(); 
    } 
    return c; 
} 

和這裏的另一個代碼來獲取給定公司

Cursor companyCode = databaseAdapter.getCompanyCode(company); 
code = companyCode.getString(companyCode.getColumnIndex(Constants.COMPANY_CODE)); 

,這裏是我的logcat的公司代碼。

06-04 12:54:48.085: E/AndroidRuntime(27134): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.uni.customercare/com.uni.customercare.ViewSummaryActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 
+0

你試圖檢查,如果遊標包含任何記錄(moveToFirst()或getCount將(例如的價值retur))? – sandrstar

+0

沒有。我不知道如何。我試圖把它放在敬酒上,看看有沒有價值,但我的應用崩潰了。 – lolliloop

+0

嘗試在getString()之前調用companyCode.getCount()以確保它包含記錄。 – sandrstar

回答

0

試試這個辦法:

定義數據庫中的輔助類此方法延伸SQLiteOpenHelper。使用該類的一個實例來調用此方法。

public HashMap<String, String> getCompanyDetails(){ 

     HashMap<String,String> company= new HashMap<String,String>(); 
     String selectQuery = "SELECT * FROM " + TABLE_COMPANY; //Change this query accordingly. 

     SQLiteDatabase db = this.getReadableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery, null); 

     cursor.moveToFirst(); 
     if(cursor.getCount() > 0){ 
      company.put(KEY_COMP_ID, cursor.getString(0)); 
      company.put(KEY_COMP_CODE, cursor.getString(1)); 
      company.put(KEY_COMP_NAME, cursor.getString(2)); 

     } 
     cursor.close(); 
     db.close(); 

     return company; 
    } 
0

簡單方式與光標企業編碼工作..

companyCode.moveToFirst(); 
while(!companyCode.isAfterLast()) { 
    //do something with companyCode.. 
    //..... 
    companyCode.moveToNext(); 
} 
companyCode.close()