728x90

안드로이드 연락처 정보를 Update 하거나 Delete 할 경우에 성명 + 휴대폰번호 기준으로 조건에 충족하는 Contact_ID 를 구하는 메소드를 구현했다.

동일한 성명이 여러개 존재하거나, 휴대폰번호가 동일한 것이 2개 이상 존재할 수도 있다.

자료 결과 반환 조건은 성명 + 전화번호는 unique 하다는 가정하에 테스트를 진행했다.


Phone.TYPE = 2 (휴대폰번호, Phone.TYPE_MOBILE) 

Phone.TYPE = 3 (사무실번호, Phone.TYPE_WORK)


// 표시 이름과 휴대폰번호를 기준으로 ContactId 구하기
public static long getContactIDFromNameAndNumber(ContentResolver contactHelper, String display_name, String number) {
    long rawContactId = -1;

    Uri contactUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    String[] projection = {Phone.CONTACT_ID, Phone.NUMBER};
    String where = Phone.DISPLAY_NAME + " = '" + display_name + "' AND " + Phone.NUMBER + " =? AND " + Phone.TYPE + " =2";
    String[] whereParams = new String[]{number};
    String sortOrder = Phone.DISPLAY_NAME + " ASC";
    Cursor cursor = null;
    try {
        cursor = contactHelper.query(contactUri, null, where, whereParams, sortOrder);
        if (cursor.moveToFirst()) {
            do {
                rawContactId = cursor.getLong(cursor.getColumnIndex(Phone.CONTACT_ID));
            } while (cursor.moveToNext());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return rawContactId;
}


위 코드는 문제점이 휴대폰번호를 010-1111-0000 과 01011110000 을 다르게 인식하여 결과가 다르게 나온다.


그래서 코드를 다시 수정 테스트를 했다.

아래 코드는 휴대폰번호 010-1111-0000 과 01011110000 을 동일하게 인식하고 같은 rawContactId 를 반환한다.

// 표시 이름과 휴대폰번호를 기준으로 ContactId 구하기
public static long getContactIdFromNameAndNumber(ContentResolver contactHelper, String display_name, String number) {
    long rawContactId = -1;

    Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    String[] projection = {PhoneLookup._ID, PhoneLookup.TYPE, PhoneLookup.DISPLAY_NAME};
    Cursor cursor = null;
    try {
        cursor = contactHelper.query(contactUri, projection, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                String PhoneName = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
                if(display_name.equals(PhoneName)){
                    rawContactId = cursor.getLong(cursor.getColumnIndex(PhoneLookup._ID));
                }
            } while (cursor.moveToNext());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return rawContactId;
}


블로그 이미지

Link2Me

,