2011-04-10 49 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 
}