Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Postal address from a contact using ContactsContract api on android

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.

like image 996
mudit Avatar asked Dec 09 '22 14:12

mudit


1 Answers

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. 
like image 85
Thorstenvv Avatar answered Dec 12 '22 02:12

Thorstenvv