Using CursorLoader to get emails causes duplication of emails

前端 未结 6 2150
攒了一身酷
攒了一身酷 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:34

    If you are worried about performance and don't want to play around with cursor again in onLoadFinished(), then there is a small hack

    I combined following two solutions from SO.

    1. select distinct value in android sqlite

    2. CursorLoader with rawQuery

    And here is my working solution:

        @Override
        public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        String tableName;
    
        /*
         * Choose the table to query and a sort order based on the code returned
         * for the incoming URI.
         */
        switch (uriMatcher.match(uri)) {
            case NOTIFICATION:
                tableName = NOTIFICATIONS_TABLE_NAME;
    
                break;
    
            case NOTIFICATION_TIMESTAMP:
    
                Cursor cursor = db.query(true, NOTIFICATIONS_TABLE_NAME, projection, selection, selectionArgs, TIMESTAMP, null, sortOrder, null);
                cursor.setNotificationUri(getContext().getContentResolver(), uri);
    
                return cursor;
    
            case DOWNLOAD:
                tableName = DOWNLOADS_TABLE;
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
    
    
        if (selection != null) {
            selection = selection + "=?";
        }
    
        Cursor cursor = db.query(tableName, projection, selection, selectionArgs, null, null, sortOrder);
    
    
        // Tell the cursor what uri to watch, so it knows when its source data
        // changes
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }
    

    If you see in this case Table name is same is first 2 cases but i created a dummy Uri to achieve this. May not be a very good approach but works perfectly.

提交回复
热议问题