2013-07-21 93 views
4

使用我現在的代碼,我只能獲取聯繫人號碼。但我想得到contact's name and contact's photo path。通過Google搜索嘗試了很多代碼,但我無法完成。試過this,但得到FileNotFoundException。有人可以通過在下面的代碼中添加代碼片段來幫助我實現嗎?從android中的聯繫人中檢索照片和姓名

public void getContact(View view) 
{ 

     Intent intent = new Intent(Intent.ACTION_PICK); 
     intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); 
     startActivityForResult(intent, 1); 

} 

protected void onActivityResult(int requestCode, int resultCode,Intent data) 
    { 
     super.onActivityResult(requestCode, resultCode, data); 

      if(resultCode==RESULT_OK && requestCode == 1) 
     { 
      if (data != null) { 
       Uri uri = data.getData(); 

       if (uri != null) { 
        Cursor c = null; 
        try { 
         c = getContentResolver().query(uri, new String[]{ 
            ContactsContract.CommonDataKinds.Phone.NUMBER, 
            ContactsContract.CommonDataKinds.Phone.TYPE }, 
           null, null, null); 

         if (c != null && c.moveToFirst()) { 
          String phoneNumber = c.getString(0); 
          int type = c.getInt(1);  
         } 
        } finally { 
         if (c != null) { 
          c.close(); 
         } 
        } 
       } 
      } 
     } 
     } 

回答

7

此代碼遍歷所有聯繫人,並得到他們的第一個名字,姓氏和照片爲位圖:

Cursor cursor = App 
      .getInstance() 
      .getContentResolver() 
      .query(ContactsContract.Contacts.CONTENT_URI, null, null, null, 
        null); 

    if (cursor != null && cursor.getCount() > 0) { 
     while (cursor.moveToNext()) { 
      long id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID)); 

      // get firstName & lastName 
      Cursor nameCur = App.getInstance().getContentResolver() 
        .query(ContactsContract.Data.CONTENT_URI, 
          null, 
          ContactsContract.Data.MIMETYPE 
            + " = ? AND " 
            + StructuredName.CONTACT_ID 
            + " = ?", 
          new String[] { 
            StructuredName.CONTENT_ITEM_TYPE, 
            Long.valueOf(id).toString() }, null); 
      if (nameCur != null) { 
       if (nameCur.moveToFirst()) { 

        String displayName = nameCur.getString(nameCur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
        if (displayName == null) displayName = ""; 

        String firstName = nameCur.getString(nameCur.getColumnIndex(StructuredName.GIVEN_NAME)); 
        if (firstName == null) firstName = ""; 
        Log.d("--> ", firstName.length()>0?firstName:displayName); 

        String middleName = nameCur.getString(nameCur.getColumnIndex(StructuredName.MIDDLE_NAME)); 
        if (middleName == null) middleName = ""; 

        String lastName = nameCur.getString(nameCur.getColumnIndex(StructuredName.FAMILY_NAME)); 
        if (lastName == null) lastName = ""; 

        lastName = middleName + (middleName.length()>0?" ":"") + lastName; 

        Log.d("--> ", lastName); 
       } 
       nameCur.close(); 
      } 

      Bitmap photo = null; 

      try { 
       InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(App.getContext().getContentResolver(), 
         ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.valueOf(id))); 

       if (inputStream != null) { 
        photo = BitmapFactory.decodeStream(inputStream); 
       } 

       if (inputStream != null) inputStream.close(); 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

      Log.d("--> ", photo); 
     } 
    } 

    if (cursor != null) { cursor.close(); } 

您還需要此權限:<uses-permission android:name="android.permission.READ_CONTACTS" />

希望有所幫助!

3

試試這個:

Uri u = objItem.getPhotoUri(); 
if (u != null) { 
     mPhotoView.setImageURI(u); 
} else { 
     mPhotoView.setImageResource(R.drawable.ic_contact_picture_2); 
} 
0

這是方法我用得到聯繫人的照片,編號和名稱,但:

接觸是通過的getId()

/** 
* @return the photo URI 
*/ 
public Uri getPhotoUri() { 
    try { 
     Cursor cur = this.ctx.getContentResolver().query(
       ContactsContract.Data.CONTENT_URI, 
       null, 
       ContactsContract.Data.CONTACT_ID + "=" + this.getId() + " AND " 
         + ContactsContract.Data.MIMETYPE + "='" 
         + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null, 
       null); 
     if (cur != null) { 
      if (!cur.moveToFirst()) { 
       return null; // no photo 
      } 
     } else { 
      return null; // error in cursor process 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return null; 
    } 
    Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long 
      .parseLong(getId())); 
    return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY); 
} 

用途是識別從一個片段來看這個東西。

在清單中設置權限。

<uses-permission android:name="android.permission.READ_CONTACTS" /> 

聲明常數:

private static final int REQUEST_CODE_PICK_CONTACT = 1; 

在我的應用程序,用戶需要選擇通過點擊一個按鈕,手機聯繫人。所以在onclick()方法,我這樣做:

contactChooserButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      startActivityForResult(new Intent(Intent.ACTION_PICK, 
      ContactsContract.Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACT); 

     } 
    }); 

添加方法來檢索照片,姓名和號碼:

private String retrieveContactNumber() { 

    String contactNumber = null; 

    // getting contacts ID 
    Cursor cursorID = getActivity().getContentResolver().query(uriContact, 
      new String[]{ContactsContract.Contacts._ID}, 
      null, null, null); 

    if (cursorID.moveToFirst()) { 

     contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID)); 
    } 

    cursorID.close(); 

    Log.e(TAG, "Contact ID: " + contactID); 

    // Using the contact ID now we will get contact phone number 
    Cursor cursorPhone = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
      new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, 

      ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " + 
        ContactsContract.CommonDataKinds.Phone.TYPE + " = " + 
        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE, 

      new String[]{contactID}, 
      null); 

    if (cursorPhone.moveToFirst()) { 
     contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
     phoneNumber = contactNumber; 
    } 

    cursorPhone.close(); 

    Log.e(TAG, "Contact Phone Number: " + contactNumber); 
    return contactNumber; 

} 

//Retrieve name 
private void retrieveContactName() { 

    String contactName = null; 

    // querying contact data store 
    Cursor cursor = getActivity().getContentResolver().query(uriContact, null, null, null, null); 

    if (cursor.moveToFirst()) { 

     // DISPLAY_NAME = The display name for the contact. 
     // HAS_PHONE_NUMBER = An indicator of whether this contact has at least one phone number. 

     contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
     personName = contactName; 
    } 

    cursor.close(); 

    Log.e(TAG, "Contact Name: " + contactName); 

} 

//Retrieve photo (this method gets a large photo, for thumbnail follow the link below) 
public void retrieveContactPhoto() { 

    Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactID)); 
    Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO); 
    try { 
     AssetFileDescriptor fd = 
       getActivity().getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r"); 
     photoAsBitmap = BitmapFactory.decodeStream(fd.createInputStream()); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

最後,在onActivityForResult方法,這樣做:

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data);   
    try { 

     if(requestCode == REQUEST_CODE_PICK_CONTACT && resultCode == Activity.RESULT_OK) { 
      Log.e(TAG, "Response: " + data.toString()); 
      uriContact = data.getData(); 
      personPhoneTextField.setText(retrieveContactNumber()); 
//the method retrieveContactNumber returns the contact number, 
//so am displaying this number in my EditText after getting it. 
//Make your other methods return data of 
//their respective types (Bitmap for photo) 

    retrieveContactPhoto(); 
    retrieveContactName(); 


     } 
    } catch (Exception exception) { 
     exception.printStackTrace(); 

    } 
} 

這是it.For活動,看看這個Android: Get Contact Details (ID, Name, Phone, Photo) Github上

相關問題