Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get contact details from contact id in Android

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!

like image 551
user1116714 Avatar asked Dec 13 '22 05:12

user1116714


2 Answers

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..

like image 174
user370305 Avatar answered Jan 04 '23 22:01

user370305


Because managedQuery is deprecated you can also use

Cursor phoneCursor = getContentResolver().query(myPhoneUri, null, null, null, null);
like image 31
ckn Avatar answered Jan 05 '23 00:01

ckn