Android📱

[Android] ContentResolver로 연락처가져오기~~!

아무루 2023. 5. 30. 21:47

 

개발 중 연락처를 가져와서 전화번호부를 기능을 만들어야 해서

찾아본 ContentResolver로 연락처 가져오기~~~

 

안드로이드 기기는 본래가 핸드폰인지라

연락처를 저장하는 기능이 존재한다.

그리고 앱개발을 하다 보면 이걸 가지고 와야 하는 경우도 존재하게 된다.

 

그럴 때 사용하는 것이 ContentResolver이다.

 

공식문서에 나와있는 방식으로도 가능

https://developer.android.com/training/contacts-provider/retrieve-names

 

연락처 목록 검색  |  Android 개발자  |  Android Developers

연락처 목록 검색 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 이 과정에서는 다음 기법을 사용하여 데이터가 전체 또는 일부 검색 문자열과 일치하는 연

developer.android.com

근데 deprecatede 된 코드도 많고 적당한 예시가 아닌 거 같아서 

ContentResolver를 이용해서 구현했다.

 

private fun getProjection() = arrayOf(
    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
    ContactsContract.CommonDataKinds.Phone.NUMBER
)

private fun ContentResolver.getCursor(projection: Array<String>) = query(
    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
    projection,
    null,
    null,
    null
)

fun onLoadContact(resolver: ContentResolver): List<ContactViewModel.Contact> {
    val projection = getProjection()
    val cursor = resolver.getCursor(projection)
    val contactList = mutableListOf<ContactViewModel.Contact>()
    if (cursor != null) {
        while (cursor.moveToNext()) {
            val nameIndex =
                cursor.getColumnIndex(projection[0])
            val numberIndex =
                cursor.getColumnIndex(projection[1])
            val name = cursor.getString(nameIndex)
            val number = cursor.getString(numberIndex)

            contactList.add(ContactViewModel.Contact(name, number))
        }
    }
    cursor?.close()
    return contactList
}

위 코드를 사용하면 전화번호부의 모든 이름과 전화번호를 가져올 수 있다.

 

getProjection에 가져오고 싶은 정보를 추가해 주면 다른 데이터도 얻어올 수 있다.

 

원리는 ContentResolver의 커서를 이용해서 무한으로 테이블에 있는 데이터를 긁어오는 간단한 방식이다.