Android ContactsContract.Display_Name returns contact phone number or any other available data

440 Views Asked by At

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?

1

There are 1 best solutions below

3
On

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.