如何从android中的电话号码获取昵称

时间:2011-12-27 16:02:31

标签: android

  

可能重复:
  How to look-up a contact's name from their phone number on Android?

如何从android中的电话号码获取昵称。使用的内容提供商。

1 个答案:

答案 0 :(得分:0)

使用以下代码:

String [] projection = { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };
Cursor cursor =
    this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                                    projection, null, null, null);
if (cursor.moveToNext()) {
    int displayNameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
    String displayName = cursor.getString(displayNameIdx);
}

我不完全确定您需要显示名称,但如果您使用ContactsContract.CommonDataKinds.StructuredName:

,您可以获得更多详细信息。
String [] projection = { ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
                         ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME };
String where = ContactsContract.Data.CONTACT_ID
               + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
String[] whereParameters =
    { contactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
Cursor cursor =
        this.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
                projection, where, whereParameters, null);
编辑:啊,现在因为我看到你想把昵称映射到电话号码。这是您从给定电话号码中选择contact_id的方式:

String [] projection =
    { ContactsContract.CommonDataKinds.Phone.CONTACT_ID };
Cursor phoneCursor =
        this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                projection, ContactsContract.CommonDataKinds.Phone.NUMBER + " = ?", 
                new String[]{number}, null);
int idIndex = phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
while (phoneCursor.moveToNext()) { 
    String id = phoneCursor.getString(numberIndex);
    Log.i(LOG_TAG, "This is the contact id associatated with the given number" + id);
} 
phoneCursor.close();