views:

103

answers:

2

Hello,

I want to get the nickname of a contact from addressbook. I start with his phone number, query it and want the nickname (aka alias) as a result.

Cursor cur = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.NUMBER + " = " + incomingNumber, null, null);

        if (cur.moveToFirst()) {
            Log.e("saymyname", cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME)));
            Log.e("saymyname", cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.LABEL)));
        }

Output of the logs is the incomingNumber (first Log.e() ) and null (second Log.e() ), but I want to get the contact's nickname!

Thanks Tom

+2  A: 

Nickname is held in a different table than the phone numbers, you have to query ContactsContract.Data.CONTENT_URI

Check my answer on this question

Pentium10
A: 

The answer above was very helpful! Thanks!

If anybody needs a sample, look at the following code:

public String accessContact(String incomingNumber) {
        if (incomingNumber == null || "".equals(incomingNumber)) {
            return "unknown";
        }

        try {
            Cursor cur = context.getContentResolver().query(Phone.CONTENT_URI, new String[] {Phone.DISPLAY_NAME, Phone.TYPE, Phone.CONTACT_ID}, Phone.NUMBER + " = " + incomingNumber, null, null);

            int nameIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
            int typeIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
            int idIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);

            String name;
            String type;
            String id;

            if (cur.moveToFirst()) {
                name = cur.getString(nameIndex);
                type = cur.getString(typeIndex);
                id = cur.getString(idIndex);
            } else {
                return "unknown";
            }

            cur = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[] {ContactsContract.Data.DATA1}, ContactsContract.Data.CONTACT_ID + " = " + id, null, null);

            int nicknameIndex = cur.getColumnIndex(ContactsContract.Data.DATA1);
            String nickname;

            if (cur.moveToFirst()) {
                nickname = cur.getString(nicknameIndex);
                if (nickname.equals(incomingNumber)) {
                    return name;
                }
                return nickname;
            } else {
                return name;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "unknown";
        }
TomTasche