views:

44

answers:

2

Hi

I am using ContactsContract api intent for showing all contacts from an activity. This intent returns an id of the contact. I need to get the postal address of this contact.

Here is the code which i am using for showing contacts:

Intent intent = new Intent(Intent.ACTION_PICK); intent.setType(ContactsContract.Contacts.CONTENT_TYPE); startActivityForResult(intent, PICK_CONTACT);

I am getting the result in the onActivityResult function.

Please help, how do i do this.

A: 

in your onActivityResult, first get the contact ID and query the ContactsContract.Data for the relevant data:

// get the contact ID

Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
cursor.moveToFirst();
long id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));
cursor.close();

// get the data package containg the postal information for the contact
cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, 
    new String[]{ StructuredPostal.STREET,
        StructuredPostal.CITY,
// add more coluns from StructuredPostal if you need them
        StructuredPostal.POSTCODE},
        ContactsContract.Data.CONTACT_ID + "=? AND " +
            StructuredPostal.MIMETYPE + "=?",
        new String[]{String.valueOf(id), StructuredPostal.CONTENT_ITEM_TYPE},
        null);


Street = cursor.getString(cursor.getColumnIndex(StructuredPostal.STREET));
Postcode = cursor.getString(cursor.getColumnIndex(StructuredPostal.POSTCODE));
City = cursor.getString(cursor.getColumnIndex(StructuredPostal.CITY)));
// etc. 
Thorstenvv
A: 

Can be done this way too (little lesser code)

Send the Intent this way:

Intent intent = new Intent(Intent.ACTION_PICK);

intent.setType(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_TYPE); startActivityForResult(intent, PICK_CONTACT);

In the onActivityResult method

Uri contactData = data.getData();
Cursor c =  managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
    String address = c.getString(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
}
Kiran