2011-07-20 33 views
2

我想從一個光標這樣的數據填充列表:如何獲取字段值而不是列名?

  myCursor = myDBA.getAllCompanies(); 
    startManagingCursor(myCursor); 

    myListAdapter = new SimpleCursorAdapter(this, R.layout.company_row, myCursor, FROM, TO); 

    myListAdapter.setViewBinder(VIEW_BINDER); 

    companiesListView.setAdapter(myListAdapter); 

我使用自定義ViewBinder裝滿兩輛TextViews並且在每行一個ImageView

private final ViewBinder VIEW_BINDER = new ViewBinder() { 
    /** 
    * Binds the Cursor column defined by the specified index to the 
    * specified view. 
    */ 
    @Override 
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) { 
     int viewId = view.getId(); 
     switch (viewId) { 
     case R.id.company_name: 
     case R.id.company_desc: 
      Log.d(TAG, "Binding TextView"); 
      TextView venueText = (TextView) view; 
      venueText.setText(cursor.getString(columnIndex)); 
      return true; 

     case R.id.company_icon: 
      Log.d(TAG, "Binding ImageView"); 
      ImageView venueIcon = (ImageView) view; 
      String iconName; 

       iconName = cursor.getString(columnIndex); //Here I get the column name not the field value 

      Resources resources = myContext.getResources(); 
      Drawable drawable = resources.getDrawable(resources 
        .getIdentifier("my.package:drawable/" 
          + iconName, null, null)); 
      venueIcon.setImageDrawable(drawable); 
      return true; 
     } 
     return false; 
    } 
}; 

我的問題是cursor.getString()方法調用返回列名稱不是字段的值,所以我得到數百行列名稱。

更新:

getAllCompanie S帶有Cursor一個moveToFirst呼叫,但我仍然得到列名:

public Cursor getAllCompanies(){ 
    Cursor s = myDB.query(TABLE, KEYS, WHERE, null, null, null, null); 
    s.moveToFirst(); 
    return s; 
} 

回答

2

你有沒有試過將光標移動到第一個指數cursor.moveToFirst();然後做cursor.getString(columnIndex);

還有另外一種方法,創建一個列表或數組將光標保存的值,訪問它裏面的所有數據通過光標迭代

while(cursor.isAfterLast()==false) 
{ 
    list.add(cursor.getString(thestringcollumnindex); 
cursor.moveToNext(); 
} 

然後就去做

iconName=list.get(columnindex); 

這個解決方案並不是最好的,但是如何達到這個目的。

+0

字符串我將第二次這樣的:'myDBA.getAllCompanies()調用'moveToFirst';',你應該罰款。 – Femi

+0

只要是在他從數據中提取數據之前調用moveToFirst並不重要,對吧? –

+0

沒錯:最簡單的方法就是將它隱藏在返回'Cursor'的函數中。如果它返回一個'Cursor'就準備好了:不需要進一步的摸索。如果'moveToFirst'失敗,則返回null並跳過整個練習。 – Femi

0

你試過了嗎?

cursor.getString(cursor.getColumnIndex("column_name")); 

它可以把你從列名

相關問題