2011-04-10 46 views
0

我想知道如果有人能夠指向我在正確的方向或借給一雙眼睛,看看我的錯誤與我的自定義遊標適配器類的列表視圖。Android:自定義光標適配器問題

基本上,我已經「工作」了,就是說它會用數據庫的名字填充listview,而不是移動到下一行。現在,它會拋出一個錯誤,而不是進入名單,所以任何幫助表示讚賞。

基本上,我有實現的閱讀從數據庫名稱和圖像路徑,並將其應用到我的自定義adapter.Here一個row.xml麻煩的是我的代碼:

public class CustomAdapter extends SimpleCursorAdapter { 

private LayoutInflater mInflater; 
private Context context; 
private int layout; 

//private Cursor c; 
String animal_name; 
String img_path; 

public CustomAdapter(Context context,int layout, Cursor c, String[] from, int[] to){ 
super(context, layout, c, from, to); 

//this.c = c; 
this.context = context; 
this.layout = layout; 
} 



@Override 
public View getView(int position, View convertView, ViewGroup parent){ 

    View row = convertView;   
    ViewWrapper wrapper = null; 

    Cursor c = getCursor(); 

    animal_name = c.getString((c.getColumnIndexOrThrow(MyDBManager.KEY_ANIMALNAME))); 
    img_path = c.getString((c.getColumnIndexOrThrow(MyDBManager.KEY_IMGPATH)));  

    if(row == null){ 
     LayoutInflater inflater = LayoutInflater.from(context); 

     row = inflater.inflate(R.layout.row, null); 
     // row is passed in as "base" variable in ViewWrapper class. 
     wrapper = new ViewWrapper(row); 

     row.setTag(row); 
    } 
    else{ 
     wrapper=(ViewWrapper)row.getTag(); 
    } 

    wrapper.getLabel().setText(animal_name); 
    wrapper.getIcon().setImageResource(R.id.icon); 

    return (row); 
}  

}

class ViewWrapper{ 
View base; 
TextView label = null; 
ImageView icon = null; 

ViewWrapper(View base){ 
    this.base = base; 
} 

TextView getLabel(){ 
    if(label== null){ 
     label=(TextView)base.findViewById(R.id.author); 
    } 
    return (label); 
} 

ImageView getIcon(){ 
    if(icon == null){ 
     icon=(ImageView)base.findViewById(R.id.icon); 
    } 
    return (icon); 
} 

}

,並已設置適配器如下

CustomAdapter mAdapter = new CustomAdapter(this, R.layout.row, myCursor, new String[]{"animal_name"}, new int[]{R.id.animal}); 
    this.setListAdapter(mAdapter); 

任何幫助,非常感謝。

回答

1

你問題是你在做row.setTag(row)。您應該將標籤設置爲ViewWrapper。

在遊標適配器中,您應該覆蓋bindview和newView而不是getView。

從10,000英尺起,它的工作方式如下: 如果視圖爲空,則GetView調用newView,並在新視圖之後調用bindView。

3

所有適配器類都可以遵循重載getView()的ArrayAdapter模式來定義 行。但是,CursorAdapter及其子類的默認實現爲 getView()。 getView()方法檢查提供的View以進行回收。如果它爲空,getView()調用 newView(),然後bindView()。如果它不爲null,getView()只是調用bindView()。 如果您要擴展CursorAdapter(用於顯示數據庫結果或 內容提供者查詢),則應該重寫newView()和bindView(),而不是使用getView()來代替 。這一切的確是刪除您如果()測試,你將不得不在getView(),並把 在一個獨立的方法測試的每一個分支,類似於如下:

public View newView(Context context, Cursor cursor, 
       ViewGroup parent) { 
    LayoutInflater inflater=context.getLayoutInflater(); 
    View row=inflater.inflate(R.layout.row, null); 
    ViewWrapper wrapper=new ViewWrapper(row); 
    row.setTag(wrapper); 
    return(row); 
} 

public void bindView(View row, Context context, Cursor cursor) { 
    ViewWrapper wrapper=(ViewWrapper)row.getTag(); 
    // actual logic to populate row from Cursor goes here 
}