2013-07-22 4 views
4

나는 사진이있어 안드로이드 전화에 저장되어 있습니다. 나는 연락처의 그림을 바꿀 수 있기를 원한다.프로그래밍 방식으로 연락처 사진 변경

내가 지금까지해온 방법은 연락처 선택 도구를 실행하고 사용자가 연락처를 선택한 다음 선택한 연락처의 URI를 가져 오는 것입니다. 이 연락처에서 관련 rawContact를 가져올 수 있으며 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) { 
     // Handle error cases. 
    } 

문제는 AssetFIleDescriptor가 항상 비어 있다는 것입니다 (길이를 호출하면 항상 -1이됩니다).

전체 솔루션을 요구하는 것이 아니며, 따라야 할 몇 가지 단서가 있습니다. StackOverflow에서 이미이 문제를 발견 할 수 없어서 도움이 될 것입니다.

편집

우리는 우리가 해결책을 찾아 그 질문을 요청할 때 항상입니다. 당신이 연락을받을 수있는이 너무 http://wptrafficanalyzer.in/blog/programatically-adding-contacts-with-photo-using-contacts-provider-in-android-example/

사진 피커, 선택한 연락처의 URI를 반환 : 나는

그래서 나는 안드로이드 링크를 포기하고 다른 그것을 공유하고 다른 하나를 찾고 싶어요. 그것의 _ID : 나는

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(); 

다음 : 다음

// 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를 얻을 수 있었다 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); 

을 그리고 이것은 마법처럼 노력하고 있습니다. 도움이 되었기 바랍니다.

+0

AndroidManifest.xml에 어떤 사용 권한이 있습니까? 연락처 선택 도구는 검색된 URI에 대한 임시 읽기 권한을 제공하지만 실제로 연락처를 업데이트하려면 WRITE_CONTACTS 권한을 설정해야합니다. – Josiah

+0

나는 READ와 WRITE_CONTACT 권한을 가지고있다. – Tristan

답변

1
String contactId ="10001"; // change it as your IDs 
    if (mBitmap != null) { 
       // Picture 
       try { 
        ByteArrayOutputStream image = new ByteArrayOutputStream(); 
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, image); 

        Uri rawContactUri = null; 
        Cursor rawContactCursor = managedQuery(
          ContactsContract.RawContacts.CONTENT_URI, 
          new String[]{ContactsContract.RawContacts._ID}, 
          ContactsContract.RawContacts.CONTACT_ID + " = " + contactId, 
          null, 
          null); 
        if (!rawContactCursor.isAfterLast()) { 
         rawContactCursor.moveToFirst(); 
         rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendPath("" + rawContactCursor.getLong(0)).build(); 
        } 
        rawContactCursor.close(); 

        ContentValues values = new ContentValues(); 
        int photoRow = -1; 
        String where111 = ContactsContract.Data.RAW_CONTACT_ID + " == " + 
          ContentUris.parseId(rawContactUri) + " AND " + ContactsContract.Data.MIMETYPE + "=='" + 
          ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'"; 
        Cursor cursor = managedQuery(
          ContactsContract.Data.CONTENT_URI, 
          null, 
          where111, 
          null, 
          null); 
        int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID); 
        if (cursor.moveToFirst()) { 
         photoRow = cursor.getInt(idIdx); 
        } 

        cursor.close(); 


        values.put(ContactsContract.Data.RAW_CONTACT_ID, 
          ContentUris.parseId(rawContactUri)); 
        values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1); 
        values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, image.toByteArray()); 
        values.put(ContactsContract.Data.MIMETYPE, 
          ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE); 
        if (photoRow >= 0) { 
         getContentResolver().update(
           ContactsContract.Data.CONTENT_URI, 
           values, 
           ContactsContract.Data._ID + " = " + photoRow, null); 
        } else { 
         getContentResolver().insert(
           ContactsContract.Data.CONTENT_URI, 
           values); 
        } 
       } catch (Exception e) { 
        Log.e("[email protected]@Image_Exception", e + ""); 
       } 
      } 
try { 
      getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); 
     } catch (Exception e) { 
      Log.e("@@@@@UPLOADERR", e + ""); 
     } 
관련 문제