Using CursorLoader to get emails causes duplication of emails

前端 未结 6 2193
攒了一身酷
攒了一身酷 2021-02-14 06:44

I am trying to get email ids of uses contacts. For that I am using Cursor Loader. There is one problem I am getting duplicate email ids also. How to remove email duplicacy. Shou

6条回答
  •  温柔的废话
    2021-02-14 07:21

    Inspired by @mars, I have a solution that does not need a modification of the adapter. The idea is to delete the duplicates of the cursor; as there is no way to do it, we create a new cursor whithout the duplicates.

    All the code is in onLoadFinished:

    @Override
        public void onLoadFinished(Loader loader, Cursor cursor) {
    
            MatrixCursor newCursor = new MatrixCursor(PROJECTION); // Same projection used in loader 
            if (cursor.moveToFirst()) {
                String lastName = "";
                do {
                    if (cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)).compareToIgnoreCase(lastName) != 0) {
    
                        newCursor.addRow(new Object[]{cursor.getString(0), cursor.getString(1), cursor.getString(2) ...}); // match the original cursor fields
                        lastName =cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    }
                } while (cursor.moveToNext());
            }
            mContactsAdapter.swapCursor(newCursor);
        }
    

提交回复
热议问题