3

I know how to retrieve contact data for specific contacts. However, i can't find a way to get all contacts plus some of their details in a single query. The following code gets all contacts having a postal address:

  Uri uri = ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI;
  String[] projection = new String[] {
    StructuredPostal._ID,
    StructuredPostal.LOOKUP_KEY,
    StructuredPostal.DISPLAY_NAME,
    StructuredPostal.STREET,
    StructuredPostal.CITY
  };
  String sortOrder = StructuredPostal.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
  Cursor c = getContentResolver().query(uri, projection, null, null, sortOrder);

But what i need are all contacts, whether they have postal address or not. Is this doable using the ContatsContract API, or do i need to create custom outer join query? Any hints on how?

compostus
  • 1,178
  • 10
  • 13

2 Answers2

4

if You have a contact ID and you want to fetch the Postal Address then use this :

         Uri postal_uri = ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI;
         Cursor postal_cursor  = getContentResolver().query(postal_uri,null,  ContactsContract.Data.CONTACT_ID + "="+contactId.toString(), null,null);
          while(postal_cursor.moveToNext())
            {
             String Strt = postal_cursor.getString(postal_cursor.getColumnIndex(StructuredPostal.STREET));
             String Cty = postal_cursor.getString(postal_cursor.getColumnIndex(StructuredPostal.CITY));
             String cntry = postal_cursor.getString(postal_cursor.getColumnIndex(StructuredPostal.COUNTRY));
            } 
            postal_cursor.close();                   
Pir Fahim Shah
  • 10,505
  • 1
  • 82
  • 81
3

All contact information in Android 2.0 is stored in a single database table. So you can get all the information you need in a single query:

Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
    null, null, null, sortOrder);

The just iterate through the data and check Data.MIMETYPE column. For example, if this column has StructuredPostal.CONTENT_ITEM_TYPE value, then you can get StructuredPostal fields from this column.

Michael
  • 53,859
  • 22
  • 133
  • 139
  • Indeed, but it requires the post-processing. I was hoping to get the right result Cursor right out of the query, so that i can feed it directly to a list view adaptor. But this will also do, thank you for the idea! – compostus May 02 '11 at 14:11
  • I think this is old and no longer valid? Looks like now phone number is stored at a different URI. – Erik B Oct 24 '17 at 22:39