4

Androidフォンに保存されている写真があります。連絡先の写真を変更できるようにしたい。

これまでに行ったことは、連絡先ピッカーを起動し、ユーザーに連絡先を選択してもらい、選択した連絡先の URI を取得することです。この連絡先から、関連する rawContact を取得でき、このコードを使用します。

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.
     }

問題は、AssetFIleDescriptor が常に空であることです (これに対して length を呼び出すと、常に -1 が返されます)。

私は解決策全体を求めているわけではありません。それを機能させるのに役立ついくつかのリードに従うだけです. StackOverflow で既にこの問題を見つけることができないようです。

編集

解決策を見つけるのは、常に質問をするときです。他の人にシェアしたい

だから私はAndroidリンクをあきらめて、別のものを見つけました: http://wptrafficanalyzer.in/blog/programatically-adding-contacts-with-photo-using-contacts-provider-in-android-example/

ピクチャ ピッカーは、選択した連絡先の Uri を返すので、これを使用して 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();

次に、 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();

次に、RawContacts の Data._ID を取得する必要がありました (上記と同じ方法)。

次に、 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);

そして、これは魅力のように機能しています。それが役に立てば幸い

4

1 に答える 1