Search code examples
androidlistviewandroid-listviewandroid-cursoradapter

Listview duplicates items with data from a CursorAdapter subclass


I have read various posts on listview duplicating items but none of them seemed to have a good solution to a listview that uses a CursorAdapter subclass.

Am trying to populate my listview with data from my database table using a class that extends CursorAdapter.

when i start the activity that has my listview for the first time. list items are not duplicated.

  • Joseph
  • Kim

but any subsequent call to this activity, the following is shown in my listview

  • Kim
  • Kim

I have read about using ViewHolder but i want a fresh copy of data in my listview from my database every time i call this activity

below is my list adapter implementation

 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;
    }
}

implementation of my activity

@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);

What should i implement to remove this duplication of listitems?


Solution

  • remove

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

    from bindView. The method is called at least cursor.getCount() times, so you don't need to loop around the cursor itself