【问题标题】:Get all item from cursor in android从android中的光标获取所有项目
【发布时间】:2009-08-20 10:35:55
【问题描述】:

我使用此代码从光标中获取项目,但它只返回我列表中的一项。那么,如何才能将所有项目都添加到我的列表中,这是我的代码?

class MyAdapter extends SimpleCursorAdapter
{
    private Context context;

    public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to)
    {
        super(context, layout, c, from, to);
        this.context = context;

    }
    public View getView(int position, View convertView, ViewGroup parent){
        Cursor cursor = getCursor();

        LayoutInflater inflater = ((Activity) context).getLayoutInflater();         
        View v = inflater.inflate(R.layout.sbooks_row, null);           
        TextView title = (TextView)findViewById(R.id.title);
        if(title != null){
            int index = cursor.getColumnIndex(SBooksDbAdapter.KEY_TITLE);
            String type = cursor.getString(index);
            title.setText(type);
        }

        TextView lyrics = (TextView)findViewById(R.id.lyrics);
        if(lyrics != null){
            int index = cursor.getColumnIndex(SBooksDbAdapter.KEY_LYRICS);
            String type = cursor.getString(index);
            lyrics.setText(type);
        }

        ImageView im = (ImageView)findViewById(R.id.icon);
        if(im!=null){
            int index = cursor.getColumnIndex(SBooksDbAdapter.KEY_FAVORITE);
            int type = cursor.getInt(index);
            if(type==1){
                im.setImageResource(android.R.drawable.btn_star_big_on);
            }
            else{
                im.setImageResource(android.R.drawable.btn_star_big_off);
            }
        }

        return v;
    }

【问题讨论】:

    标签: android list cursor


    【解决方案1】:

    CursorAdapter 的行为与其他列表适配器稍有不同 - 而不是在 getView() 中,这里的魔力发生在 newView() 和 bindView() 中,所以我认为 getView() 不是正确的覆盖方法。

    您可能只会得到一个结果,因为在创建第一行之后,CursorAdapter 期望 bindView() 插入新数据并重用已经膨胀的行,而您期望 getView() 这样做。

    我建议您尝试将代码移至 newView() 以扩展视图,并尝试将 bindView() 移至执行填充行的实际逻辑。

    祝你好运,让我们随时了解结果。

    【讨论】:

    • 您好,我尝试根据您的建议编辑我的代码。我使用 newView()、bindView() 函数,它返回所有项目。但是我的 Listview 仍然有问题,它显示不正常。我的意思是,当我上下拖动 scollbar 时,它的显示会有所不同。我可以忘记什么吗?
    • 项目无法正常显示是什么意思?如果您看到旧项目出现,而不是新项目(使用普通适配器发生在我身上),那么您的回收逻辑(bindView())应该有问题。 P.S.我还建议您使用 ViewHolder 模式,如下所述:youtube.com/watch?v=N6YdwzAvwOA at 0:09:02。
    • 该视频链接对于任何想了解 ListView 下发生的事情的人都非常有帮助。谢谢迪米塔!
    【解决方案2】:

    我假设 getCursor() 方法返回的游标正在正确检索表的所有行,您必须在访问一行数据之前显式地将游标移动到某个位置,因此在 getView 的开头() 方法你必须调用。

    cursor.moveToPosition(position);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      相关资源
      最近更新 更多