我已经阅读了关于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);


我应该采取什么措施来消除重复的列表项?

最佳答案

去掉

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


来自bindView。该方法至少调用了cursor.getCount()次,因此您无需在游标本身周围循环

08-17 11:30
查看更多