【问题标题】:Listview duplicates items with data from a CursorAdapter subclassListview 使用来自 CursorAdapter 子类的数据复制项目
【发布时间】:2015-10-27 09:15:32
【问题描述】:

我已经阅读了关于 listview 复制项目的各种帖子,但似乎没有一个对使用 CursorAdapter 子类的 listview 有很好的解决方案。

我正在尝试使用一个扩展 CursorAdapter 的类,用我的数据库表中的数据填充我的列表视图。

当我开始有我的列表视图的活动时第一次。列表项不重复。

  • 约瑟夫

但是对该活动的任何后续调用,我的列表视图中都会显示以下内容

我已阅读有关使用 ViewHolder 的信息,但我希望在我的列表视图中从我的数据库中获得一份新的数据副本每次我调用此活动时

下面是我的列表适配器实现

 public class ChatAdapter extends CursorAdapter {

    private LayoutInflater cursorInfrlater;
    View view;

    public ChatAdapter(Context context,Cursor cursor, int flags){
        super(context,cursor,flags);
        cursorInfrlater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public void bindView(View view , Context context ,Cursor cursor){

        cursor.moveToFirst();
        while(!cursor.isAfterLast()){

            TextView name =(TextView) view.findViewById(R.id.sender_name);
            name.setText(cursor.getString(cursor.getColumnIndex(ChatHistory.COLUMN_NAME_SENDER_NAME)));
            TextView message =(TextView) view.findViewById(R.id.message);
            message.setText(cursor.getString(cursor.getColumnIndex(ChatHistory.COLUMN_NAME_MESSAGE)));
            TextView unread =(TextView) view.findViewById(R.id.counter);
            unread.setText(Integer.toString(cursor.getInt(cursor.getColumnIndex(ChatHistory.COLUMN_NAME_UNREAD_MESSAGES))));

            cursor.moveToNext();
        }

    }
    @Override
    public View newView(Context context,Cursor cursor, ViewGroup viewGroup){
        view = cursorInfrlater.inflate(R.layout.chat_row_layout,viewGroup,false);
        return view;
    }
}

我的活动的实施

@Override
    protected void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        setContentView(R.layout.chat_displayer);

        final ChatMessages cmc = new ChatMessages();
        cmc.deleteNotifications(this);
        ChatAdapter chatAdapter = cmc.getChatHistory(this);

        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(chatAdapter);

我应该实施什么来删除重复的列表项?

【问题讨论】:

  • 只使用SimpleCursorAdapter,不需要扩展任何东西,你只需创建一个适配器并调用setAdapter,就可以了
  • 来自CursorAdapter.bindView(...) 的文档 cursor-从中获取数据的光标。 光标已经移动到正确的位置。
  • @Selvin 是的。我从下面黑带的回答中了解到这一点
  • @pskink 我不认为SimpleCursorAdapter 可以满足我用数据填充列表项行中的各种视图的所有需求
  • 但我认为是这样,试试吧,你会节省很多时间和代码中可能出现的错误

标签: android listview android-listview android-cursoradapter


【解决方案1】:

删除

 cursor.moveToFirst();
 while(!cursor.isAfterLast()){
 cursor.moveToNext(); 

来自bindView。该方法至少被调用cursor.getCount() 次,因此您不需要循环游标本身

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多