I have an image that is stored on an Android phone. I want to be able to change the image of a contact.
What I have done so far is to start the contact picker, select the user, and then get the URI of the selected contact. From this contact, I can get the associated rawContact, and I use this code .
Uri rawContactPhotoUri = Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.DisplayPhoto.CONTENT_DIRECTORY); try { AssetFileDescriptor fd = getContentResolver().openAssetFileDescriptor(rawContactPhotoUri, "rw"); OutputStream os = fd.createOutputStream(); os.write(photo); os.close(); fd.close(); } catch (IOException e) {
The problem is that AssetFIleDescriptor is always empty (when I find the length on it, we always get -1).
I am not asking for the whole solution, just some of them lead to something that can help me with this. I cannot find this problem already on StackOverflow, so any help would be appreciated.
EDIT
Whenever we ask a question, we always find a solution. I want to share it with others.
So, I refused the link to android and found another one: http://wptrafficanalyzer.in/blog/programatically-adding-contacts-with-photo-using-contacts-provider-in-android-example/
The image picker returns the Uri of the selected contact, so with this you can get Contact._ID:
// This is onActivityResult final Uri uri = data.getData(); final Cursor cursor1 = getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); final long contactId = cursor1.getLong(cursor1.getColumnIndex(Contacts._ID); cursor1.close();
Then I had to get RawContactId:
final Cursor cursor2 = getContentResolver().query(RawContacts.CONTENT_URI, null, RawContacts.Contact_ID + "=?", new String[] {String.valueOf(contactId)}, null); cursor2.moveToFirst(); final long rawContactId = cursor2.getLong(cursor2.getColumnIndex(RawContacts._ID)); cursor2.close();
Then I had to get Data._ID from RawContacts (same as above).
Then I used ContentProviderOperations:
final ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI) .withSelection(Data._ID, dataId), .withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, byteArrayOfThePicture); getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
And it works like a charm. Hope this helps.