2013-06-04 47 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()