Qasim
Qasim

Reputation: 1704

How to get all contacts full name and phone number, only if they have a phone number?

I am trying to get all contacts that have a phone number, and record their full name and phone number, (and in the future, their contact photo), but I am stuck. here is my code:

String contacts = "";

    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 (hasPhone == "1") {
           contacts += cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)) + ":" + "how to get number?" + "|";
       }
    }
    cursor.close();

String hasPhone should contain "1" if the contact has a phone number, then add that name and the persons phone number to the "contact" string. Even though hasPhone does contain "1", (checked from logcat) no code in the condition statement runs. Also, how do you get the phone number, there is nothing in ContactsContract.Contacts for number.

Upvotes: 1

Views: 1574

Answers (2)

Francesco Vadicamo
Francesco Vadicamo

Reputation: 5542

Try this:

if (Integer.parseInt(hasPhone) > 0) { 
    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +"="+ contactId, null, null); 
    phones.moveToNext(); //if you are interested in all contact phones do a while()
    String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
    phones.close();
    contacts += cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)) + ":" + phoneNumber + "|";
}

Upvotes: 1

GalDude33
GalDude33

Reputation: 7130

Change to:

hasPhone.equals("1")

== operator check for object equality, that is to say, if hasPhone is the same Object as "1" which is clearly false.

You want to check for Lexicographic equality, so you should use String's equals method, which compare both Objects string equality, meaning, checks if both have the same order of characters.

Moreover, consider using the LookupKey, as described here: http://developer.android.com/resources/articles/contacts.html

If you want to save future reference for specific contact.

Upvotes: 1

Related Questions