Get contact details from contact id in Android

user1116714 picture user1116714 · Jan 28, 2012 · Viewed 12.1k times · Source

I want to get several contact details from a contact list view. I have this code:

list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
        //HERE I WANT TO GET CONTACT DETAILS FROM THE ID PARAMETER

        Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, Uri.encode(id));
        Cursor c = getContentResolver().query(lookupUri, new String[]{Contacts.DISPLAY_NAME}, null,null,null);
        try {
              c.moveToFirst();
              String displayName = c.getString(0);
        } finally {
              c.close();
        }

}

But I get this exception: IllegalArgumentException, Invalid lookup id (when I call query method from cursor). So I dont know how to get a valid lookup id from the item list.

Any idea? thanks!

Answer

user370305 picture user370305 · Jan 28, 2012

Here id means, A contact id for which you want to fetch the contact details,

The simply code for getting phone number for a particular contact id is like,

                    // Build the Uri to query to table
                    Uri myPhoneUri = Uri.withAppendedPath(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, id);

                    // Query the table
                    Cursor phoneCursor = managedQuery(
                            myPhoneUri, null, null, null, null);

                    // Get the phone numbers from the contact
                    for (phoneCursor.moveToFirst(); !phoneCursor.isAfterLast(); phoneCursor.moveToNext()) {

                        // Get a phone number
                        String phoneNumber = phoneCursor.getString(phoneCursor
                                .getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));

                        sb.append("Phone: " + phoneNumber + "\n");
                    }
                }

So, from your question I have to doubt for id parameter which are you sing in your uri just clear that, Also in my example the id is string type...

Hope you will understand it.

Update: Uri.encode(id) instead of just pass id in string format.

Thanks..