user5781295
user5781295

Reputation:

Can't detect existing phone number

I want to see if a contact exists in the contacts database.I have came up this code:

 public static boolean contactExists(Activity _activity, String number){
        Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(number));
        String[] mPhoneNumberProjection = { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup.DISPLAY_NAME };
        Cursor cur = _activity.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);
        try {
            if (cur.moveToFirst()) {
                return true;
            }
        } finally {
            if (cur != null)
                cur.close();
        }
        return false;
    }

But it gives me always false ,tho the contact exists on the device. Also i have integrated the permission in the manifest.

Upvotes: 3

Views: 46

Answers (1)

user5781295
user5781295

Reputation:

After few hours I have found the mistake ,basically on some devices it might happen that the code above won't work.To be 100% sure you will need to use this code:

 public String get_name() {

        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                null, null, null);

        if (cur.getCount() > 0) {

            while (cur.moveToNext()) {
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

                    System.out.println("name : " + name + ", ID : " + id);
                    if (name.equals(number)) {
                        title_holder = name;
                        break;
                    }else{
                        title_holder = number;
                        break;
                    }

                }
            }
        }
        return title_holder;
    } 

As you see it lists all contacts from the device ,than simply you can check if it matches with the number that you are giving.

A simpler solution:

 String myPhone = getCallName.substring(16, getCallName.length() - 4);

            if (!myPhone.matches("^[\\d]{1,}$")) {
                myPhone = context.getString(R.string.withheld_number);
            } else if (listDir.get(i).getUserNameFromContact() != myPhone) {
                myPhone = listDir.get(i).getUserNameFromContact();
            }

Upvotes: 3

Related Questions