Kontaktbild programmgesteuert ändern
Ich habe ein Bild, das im Android-Handy gespeichert ist. Ich möchte das Bild eines Kontakts ändern können.
Bisher habe ich die Kontaktauswahl gestartet, den Benutzer einen Kontakt auswählen lassen und dann die URI des ausgewählten Kontakts abgerufen. Über diesen Kontakt kann ich den dazugehörigen rawContact beziehen und verwendedieser 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) {
// Handle error cases.
}
Das Problem ist, dass der AssetFIleDescriptor immer leer ist (wenn ich length aufrufe, bekommen wir immer -1).
Ich frage nicht nach der gesamten Lösung, sondern nur nach einigen Hinweisen, die mir dabei helfen können, dass dies funktioniert. Ich kann dieses Problem nicht auf StackOverflow finden, daher wäre jede Hilfe willkommen.
BEARBEITEN
Immer wenn wir Fragen stellen, finden wir die Lösung. Ich möchte es für andere teilen
Also habe ich den Android-Link aufgegeben und einen anderen gefunden:http://wptrafficanalyzer.in/blog/programatically-adding-contacts-with-photo-using-contacts-provider-in-android-example/
Die Bildauswahl gibt den Uri des ausgewählten Kontakts zurück, damit Sie die Contact._ID davon erhalten können:
// 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();
Dann musste ich mir die RawContactId besorgen:
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();
Dann musste ich die Data._ID der RawContacts abrufen (genauso wie oben).
Dann habe ich die ContentProviderOperations verwendet:
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);
Und das funktioniert wie Charme. Ich hoffe es hilft