You will have a different code to update the photo, and then add the photo to a contact that does not have it. From your description above, I believe that you are trying to insert an image and not refresh the image, but here is the code for both:
if(hasPhoto(resolver, id) == true) { int photoRow = -1; String where = ContactsContract.Data.RAW_CONTACT_ID + " = " + id + " AND " + ContactsContract.Data.MIMETYPE + " =='" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'"; Cursor cursor = resolver.query(ContactsContract.Data.CONTENT_URI, null, where, null, null); int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID); if (cursor.moveToFirst()) { photoRow = cursor.getInt(idIdx); } cursor.close(); // Update current photo ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI) .withSelection(ContactsContract.Data._ID + " = ?", new String[] {Integer.toString(photoRow)}) .withValue(ContactsContract.Data.RAW_CONTACT_ID, id) .withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE) .withValue(ContactsContract.Data.DATA15, photoBytes) .build()); try { resolver.applyBatch(ContactsContract.AUTHORITY, ops); } catch (RemoteException e) { } catch (OperationApplicationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // Create new photo entry int rawContactId = -1; Cursor cursor = resolver.query(ContactsContract.RawContacts.CONTENT_URI, null, ContactsContract.RawContacts.CONTACT_ID + "=?", new String[] {id}, null); if(cursor.moveToFirst()) { rawContactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.RawContacts._ID)); if(rawContactId > -1) { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValue(ContactsContract.Data.RAW_CONTACT_ID, rawContactId) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photoBytes) .build()); try { resolver.applyBatch(ContactsContract.AUTHORITY, ops); } catch (RemoteException e) { } catch (OperationApplicationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
The difference is that if you update an existing photo, you use the newUpdate function, but if you insert a photo to a contact that has never had one, you use newInsert
source share