1

I'm using the code below to get contacts name from the phonebook

Uri contactUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor phones  = getContentResolver().query(contactUri,null,null,null,null);

    while (phones.moveToNext())
    {
        String name   = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

        if (name != null)
        {
            names += name + ",";
        }
    }
    phones.close();

I've noticed that when there is a contact that was saved without a name, the above code will return the phone number as the contact name. I understand that this is how android work in case the contact was saved without a name. But I have to prevent this behaviour and force it to return null or empty string in case there is no "Display_Name"..

is it possible?

Elior
  • 3,178
  • 6
  • 37
  • 67

1 Answers1

0

You can add this after getting name and before the if statement.

if(text.matches("[0-9]+")) // use "[0-9\-]+" if phone number has - too
    continue;

This would check if the value returned contains only numerical value. If yes then it would skip the rest of the loop code.

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
  • 1
    Yes I know I can do this, but I'm asking if there is another way to prevent this behaviour? because sometimes people can save the phone number in both name and phone number fields – Elior Feb 27 '16 at 16:40
  • I don't think cursor will return null when there is definitely something stored in that field. – Rohit5k2 Feb 27 '16 at 16:42
  • 1
    I think you didn't understand my question. I added on my device a contact without a name, I saved only the phone number. Now when I use the code above, and asking the name of each contact, I expected that the name of this particular contact will be empty, because there is no name. But, something else happened, the result that was returned as the name of this contact was his phone number – Elior Feb 27 '16 at 17:21