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

,
728x90

CONTACT_ID 를 구했다는 가정하에 연락처를 삭제하는 메소드이다.

메소드는 2개 모두 잘 동작함을 확인하고 적어둔다.

// 구한 ID 기준으로 연락처 삭제
public static void deleteContactFromRawContactID(ContentResolver contactHelper, long CONTACT_ID) {
    String where = RawContacts.CONTACT_ID + " = " + String.valueOf(CONTACT_ID);
    contactHelper.delete(RawContacts.CONTENT_URI, where, null);
} 

 // 구한 ID 기준으로 연락처 삭제
public static void deleteContactFromContactId(ContentResolver contactHelper, long ContactId) {
    Uri contactUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    String[] projection = null;
    String where = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?";
    String[] whereParams =new String[] { String.valueOf(ContactId) };
    String sortOrder = null;

    Cursor cursor = contactHelper.query(contactUri, projection, where, whereParams, sortOrder);
    if(cursor.moveToFirst()){
        try {
            do {
                String lookupKey = cursor .getString(cursor .getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
                Uri uri = Uri.withAppendedPath( ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
                contactHelper.delete(uri, null, null);
            } while (cursor.moveToNext());
        } catch (Exception e){
            e.getStackTrace();
        }
    }
}


전화번호로 CONTACT_ID 를 구하는 메소드

// 전화번호에서 구한 PhoneLookup._ID 가 RawContacts.ContactID 와 동일함
public static long getContactIDFromNumber(ContentResolver contactHelper, String number) {
    long rawContactId = -1;
    Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    String[] projection = {PhoneLookup._ID};
    Cursor cursor = null;

    try {
        cursor = contactHelper.query(contactUri, projection, null, null, null);
        if (cursor.moveToFirst()) {
            System.out.println("PhoneLookup._ID from number : " + cursor.getLong(cursor.getColumnIndex(PhoneLookup._ID)));
            rawContactId = cursor.getLong(cursor.getColumnIndex(PhoneLookup._ID));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if(cursor != null) {
            cursor.close();
        }
    }
    return rawContactId;
}



블로그 이미지

Link2Me

,
728x90

안드로이드 연락처 앱에 있는 연락처를  선택한 것만 삭제하는 메소드(bulkDelete) 와 모든 연락처를 삭제하는 메소드다.


public class ContactHelper {

    // 연락처 총개수 파악
    public static int getContactsTotalCount(ContentResolver contactHelper) {
        Cursor cursor = contactHelper.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        return cursor.getCount();
    }

    public static void bulkDelete(ContentResolver contactHelper,long[] ids){
        if (ids.length == 0) { // 삭제할 데이터가 없으면
            return;
        }
        StringBuilder where=new StringBuilder();
        where.append(RawContacts.CONTACT_ID);
        where.append(" IN (");
        where.append(Long.toString(ids[0]));
        for (int i=1; i < ids.length; i++) {
            where.append(',');
            where.append(Long.toString(ids[i]));
        }
        where.append(')');
        try {
            contactHelper.delete(RawContacts.CONTENT_URI,where.toString(),null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 모든 연락처 삭제
    public static void deleteAllContact(ContentResolver contactHelper) {
        contactHelper.delete(RawContacts.CONTENT_URI, null, null);
    }
}


사용법

long[] ids = new long[]{16258,15265,15441,15542,16278};
ContactHelper.bulkDelete(getContentResolver(), ids);


위와 같이 수동으로 해당 CONTACT_ID를 직접 적어주고 테스트를 했다.

하지만 앱으로 구현한다면, CustomListView 에서 체크박스를 선택한 것만 삭제되도록 구현하면 될 것이다.

체크한 것만 ArrayList 에 담고 ArrayList 를 배열로 변환한 다음에

ContactHelper.bulkDelete(getContentResolver(), ids);

를 실행하면 될 것이다.

다만 IN 안에 들어가는 인수의 개수를 어느 범위까지 허용하는지 여부는 테스트를 안해봐서 장담할 수가 없다.


성명(display_name) 과 전화번호, CONTACT_ID 를 구할 수 있는 Cursor 메소드

    // Display Name 이 포함된 모든 Cursor 반환
    public static Cursor getContactCursorFromDisplayNameLIKE(ContentResolver contactHelper, String display_name) {

        // 검색할 칼럼 정하기, null 이면 모든 필드
        String[] projection = {Phone.CONTACT_ID,Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER};
        // Cursor를 얻기 위한 쿼리 조건
        String where = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " like \'%" + display_name + "%\'";
        String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
        Cursor cursor = null;

        try {
            if (display_name != null && !display_name.equals("")) {
                cursor = contactHelper.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, where, null,
                        sortOrder);
            } else {
                cursor = contactHelper.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null,
                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
            }
            cursor.moveToFirst();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return cursor;
    }

 public class MainActivity extends AppCompatActivity {
    private ArrayList<String> contactRawContactID;
    private ArrayList<String> contactDataID;
    private ArrayList<String> contactNames;
    private ArrayList<String> contactNumbers;
    ArrayAdapter<String> adapter;
    ListView listView;
    private Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.list);
        TextView tv_getCount = (TextView) findViewById(R.id.tv_getContactCount);
        tv_getCount.setText("총 " + String.valueOf(ContactHelper.getContactsTotalCount(getContentResolver())) + " 개");

        contactRawContactID = new ArrayList<String>();
        contactDataID = new ArrayList<String>();
        contactNames = new ArrayList<String>();
        contactNumbers = new ArrayList<String>();

        cursor = ContactHelper.getContactCursorFromDisplayNameLIKE(getContentResolver(), "");
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            contactRawContactID.add(cursor.getString(0));
            contactDataID.add(cursor.getString(1));
            contactNames.add(cursor.getString(2));
            contactNumbers.add(cursor.getString(3));
            cursor.moveToNext();
        }

        adapter = new MyAdapter(this, android.R.layout.simple_list_item_1, R.id.tvNameMain, contactNames);
        listView.setAdapter(adapter);

    }

    private class MyAdapter extends ArrayAdapter<String> {

        public MyAdapter(Context context, int resource, int textViewResourceId, ArrayList<String> conNames) {
            super(context, resource, textViewResourceId, conNames);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = setList(position, parent);
            return row;
        }

        private View setList(final int position, ViewGroup parent) {
            LayoutInflater inf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View row = inf.inflate(R.layout.liststyle, parent, false);

            TextView tvRawContactID = (TextView) row.findViewById(R.id.tvRawContactID);
            TextView tvDataID = (TextView) row.findViewById(R.id.tvDataID);
            TextView tvName = (TextView) row.findViewById(R.id.tvNameMain);
            TextView tvNumber = (TextView) row.findViewById(R.id.tvNumberMain);

            tvRawContactID.setText("RawContact_ID : " + contactRawContactID.get(position));
            tvDataID.setText("Data_ID : " + contactDataID.get(position));
            tvName.setText(contactNames.get(position));
            tvNumber.setText("No: " + contactNumbers.get(position));

            return row;
        }
    }
}


블로그 이미지

Link2Me

,