views:

7857

answers:

11

Hi.

I'm working on Android 2.0 and am trying to receive a list of all contacts.

Since android.provider.Contacts.People is deprecated, I have to use android.provider.ContactsContract, But I can't find a proper example of how to use it (ex: retrieve a list of all contacts on the phonebook).

Anyone knows how to implement it?

Thanks!

+21  A: 

Hi,

I'm a Android dev by hobby so bare with me if I'm not that elegant with this code.

You can loop through your phone contacts like this:

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, 
    null, null, null, null); 
  while (cursor.moveToNext()) { 
   String contactId = cursor.getString(cursor.getColumnIndex( 
     ContactsContract.Contacts._ID)); 
   String hasPhone = cursor.getString(cursor.getColumnIndex( 
     ContactsContract.Contacts.HAS_PHONE_NUMBER)); 
   if (Boolean.parseBoolean(hasPhone)) { 
                // You know have the number so now query it like this
    Cursor phones = getContentResolver().query( 
      ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
      null, 
      ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, 
      null, null); 
    while (phones.moveToNext()) { 
     String phoneNumber = phones.getString( 
       phones.getColumnIndex( 
         ContactsContract.CommonDataKinds.Phone.NUMBER));                 
    } 
    phones.close(); 
   } 
   Cursor emails = getContentResolver().query( 
     ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
     null, 
     ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, 
     null, null); 
   while (emails.moveToNext()) { 
                // This would allow you get several email addresses 
    String emailAddress = emails.getString( 
      emails.getColumnIndex( 
        ContactsContract.CommonDataKinds.CommonDataColumns.DATA)); 
   } 
   emails.close(); 
  } 
  cursor.close();

Additionally, you can loop through your contacts and simply get the name and phone number like this:

Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

while(people.moveToNext()) {
 int nameFieldColumnIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
     String contact = people.getString(nameFieldColumnIndex);
 int numberFieldColumnIndex = people.getColumnIndex(PhoneLookup.NUMBER);
     String number = people.getString(nameFieldColumnIndex);
}

people.close();

Furthermore, if you need to get things like notes from a contact then you will need to use a different URI, like the following (feel free to use this method):

private String getNote(long contactId) { 
  String note = null; 
  String[] columns = new String[] 
                                   { ContactsContract.CommonDataKinds.Note.NOTE }; 
  String where = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
  String[] whereParameters = new String[]{Long.toString(contactId), 
    ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE}; 
  Cursor contacts = getContentResolver().query 
  (ContactsContract.Data.CONTENT_URI, projection, where, 
    whereParameters, null); 
  if (contacts.moveToFirst()) { 
   rv = contacts.getString(0); 
  } 
  contacts.close(); 
  return note; 
 }

Notice this time I used not only the contact id but the mime type for the query.

Android FTW!

Javier Figueroa
That was perfect Javier, thanks for this, I had to adapt it a bit for my purpose (check if a contact is in to avoid adding again). Here is my code if you want to add it to your post : String[] contactNameColumn = { ContactsContract.Contacts.DISPLAY_NAME }; Cursor checkContactInDatabase = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, contactNameColumn, ContactsContract.Contacts.DISPLAY_NAME + "=" + "'" + name + "'", null, null);if (checkContactInDatabase.moveToFirst()) {int nameFieldColumnIndex = checkContactInDatabase.getColumnIndex(PhoneLookup.DISPLAY_NAME);
Sephy
String contact = checkContactInDatabase.getString(nameFieldColumnIndex); Toast.makeText(Contact.this, contact + " " + getString(R.string.alreadySaved), Toast.LENGTH_SHORT).show(); } else { Intent i = new Intent(Intent.ACTION_INSERT_OR_EDIT); i.setType(Contacts.CONTENT_ITEM_TYPE); i.putExtra(Insert.NAME, name); i.putExtra(Insert.PHONE, phone); i.putExtra(Insert.COMPANY, companie); i.putExtra(Insert.POSTAL, adresse); startActivity(i); } checkContactInDatabase.close();
Sephy
+1  A: 

This part wouldn't work for me:

 while (phones.moveToNext()) { 
     String phoneNumber = phones.getString( 
       phones.getColumnIndex( 
         ContactsContract.CommonDataKinds.Phone.NUMBER));                 
    } 

If I use this, though, it does:

 while (phones.moveToNext()) { 
                                  String pdata = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
                                  Log.v("DATA",pdata);
}
vanevery
A: 

Hi Javier,

I used the method that you suggested to query the Name and Phone Number. The only difference was that I added a "where clause" for filtering the name using a Edit Text.

PhoneLookup.DISPLAY_NAME + "='"+ name.getText().toString() + "'"

I received the following error on the Console.

05-20 14:22:36.999: ERROR/AndroidRuntime(5595): java.lang.IllegalStateException: get field slot from row 0 col -1 failed

Ashish
A: 

Hi,

anyone who knows how to query for the special owner contact? (HTC Desire)

Thanks,

Nicholas

Nicholas
You're better off posting this as a separate question, if the answer to this question didn't help you. More people are likely to see your question and answer it well if you ask a new question than if you hide a question in the answers to another question.
sth
A: 

Hi,

I tried to get the phone number by using the following two ways:

while (phones.moveToNext()) {
String pdata = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA)); Log.v("DATA",pdata); }

and while (phones.moveToNext()) {
String phoneNumber = phones.getString(
phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
}

neither works, as getColumnIndex returns -1 in both case. I'm using Motorola Milestone to test it.

what's your phone model if either of the above can work on your phone?

Any other ways to retrieve phone number?

Thanks a lot.

zbc

zbc
+1  A: 

On Android 2.1 this code doesn't work:

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) { 
//...
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); 
if (Boolean.parseBoolean(hasPhone)) { 
//...

it should be:

int hasPhone = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone == 1) {
 //...

values are 0 and 1. "1" and "0" strings are not convertable to boolean.

VaNTa
A: 

vanevery, this code:

while (phones.moveToNext()) { 
  String data = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));                 
} 

also works perfectly on 2.1 as:

while (phones.moveToNext()) { 
  String data = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
}

see the value of those constants, are identical - so both version works fine.

VaNTa
A: 

Hi, I am using the code below to Check if the selected record has any number, but unfortunately I get the IllegalStateException when I used the following code at line where I check the .HAS_PHONE_NUMBER. I get the Name of contact but not able to get the number of Phone numbers in that particular contact and I get the IllegalStateException

as

public void onActivityResult(int requestCode, int resultCode, Intent data)
{
 super.onActivityResult(requestCode, resultCode, data);
 switch(requestCode)
 {
  case  ADD_FROM_CONTACTS: 
  {

   if(resultCode==Activity.RESULT_OK)
   {
    Uri contact = data.getData();
    Cursor c = null;

    c = managedQuery(contact, null, null, null, null);
    //startManagingCursor(c);
    if (c.moveToFirst()) 
    {
     String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

        String contact_id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
        int hasNum = 0;

         try
            {
             //hasNum = Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
             c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
            }
            catch(Exception e)
            {

                                            //here I got the Illegal State Exception
            }
                 }
           }
     }}}
DMatt
A: 

Hi,

I've tried everything on this post and I have not yet been able to successfully retrieve a contact's phone number. The closest I've come to has been retrieving an ID. Can anyone help?

I tried the following code provided by the android hobbyist:

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); while (cursor.moveToNext()) { String contactId = cursor.getString(cursor.getColumnIndex( ContactsContract.Contacts._ID)); String hasPhone = cursor.getString(cursor.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER));

                        int nameIndex = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);

                        if (Boolean.parseBoolean(hasPhone)) {
                            // We have a phone number, so let's query this:

                            Cursor phones = getContentResolver().query(
                                      ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                                      null, 
                                      ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, 
                                      null, null);

                            while (phones.moveToNext()) {
                                // Get the phone number.  If your contact has combined several 
                                // raw contacts, you might get a duplicated number.)
                                //

                                String name = cursor.getString(nameIndex);
                                String phoneNumber = phones.getString(
                                                        phones.getColumnIndex(
                                                                 ContactsContract.CommonDataKinds.Phone.NUMBER));

                                Toast.makeText(SampleProvider.this, name + ": " + phoneNumber, Toast.LENGTH_SHORT).show();               

                            }
                            phones.close();
                        }

                    } 
+1  A: 

@user473326

Hi look at this tutorial, hope this will help you.

Android Essentials: Using the Contact Picker-

http://mobile.tutsplus.com/tutorials/android/android-essentials-using-the-contact-picker/

Creative-MITian