안드로이드 전화번호부(Contacts) 가져오기 예제 소스
안드로이드에서 전화번호부는 URI와 Cursor를 쓰면 쉽게 받아올 수 있다.
하지만 SDK 버전업이 되면서 기존에 쓰던 소스에 문제가 발생해서
살짝 뜯어 고치느라 애를 먹었다 -.-;
그냥 단순히 SimpleCursorAdapter를 쓰면 되지만(ApiDemo에도 있듯이)
리스트뷰에 체크박스를 추가하게 되면 체크가 풀렸다가 생겼다가... 생각처럼 잘 컨트롤이 되지 않는 문제가 생긴다.
어느 블로그에서 보니, ui를 최적으로 돌리려다 보니 position을 기억못하는 문제로 봤었는데.
거기서도 SimpleCursorAdapter가 아닌 ListAdapter를 쓰고 있었따... -_-;
ListAdapter에서 전화번호부를 가져오는 방법을 여기저기서 찾다가...
결국은 깨끗하게 포기하고 오늘도 막코딩에 돌입했다.
프로젝트 소스 다운은 여기를... ->
01 |
package com.GetContact; |
03 |
import android.app.ListActivity; |
04 |
import android.database.Cursor; |
05 |
import android.net.Uri; |
06 |
import android.os.Bundle; |
07 |
import android.provider.ContactsContract; |
08 |
import android.provider.ContactsContract.Contacts; |
09 |
import android.util.Log; |
10 |
import android.widget.ArrayAdapter; |
11 |
import android.widget.ListView; |
13 |
public class GetContact extends ListActivity |
18 |
public void onCreate(Bundle savedInstanceState) |
20 |
super .onCreate(savedInstanceState); |
22 |
Cursor cursor = getURI(); |
24 |
int end = cursor.getCount(); |
25 |
Log.d(tag, "end = " +end); |
27 |
String [] name = new String[end]; |
30 |
if (cursor.moveToFirst()) |
33 |
int idIndex = cursor.getColumnIndex( "_id" ); |
38 |
int id = cursor.getInt(idIndex); |
39 |
name[count] = cursor.getString( 1 ); |
42 |
Log.d(tag, "id=" + id + ", name[" +count+ "]=" + name[count]); |
45 |
} while (cursor.moveToNext() || count > end); |
48 |
setListAdapter( new ArrayAdapter<string>( this , android.R.layout.simple_list_item_multiple_choice, name)); |
50 |
final ListView listView = getListView(); |
51 |
listView.setItemsCanFocus( false ); |
52 |
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); |
55 |
private Cursor getURI() |
58 |
Uri people = Contacts.CONTENT_URI; |
61 |
String[] projection = new String[] { Contacts._ID, Contacts.DISPLAY_NAME, Contacts.HAS_PHONE_NUMBER }; |
64 |
String[] selectionArgs = null ; |
65 |
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC" ; |
67 |
return managedQuery(people, projection, null , selectionArgs, sortOrder); |
main.xml은 원래 그대로 둬도 된다. android에서 제공하는 simple_list_item_multiple_choice.xml을 가져와 쓴다.
다른 xml로 바꾸어 보았으나... VM 떡실신 ㅠㅠ 커스텀어댑터로 사용하는 방법은 더 찾아봐야 할듯하다.
왼쪽 사진.
log.d로 본 목록들. 맨 위에 end = 92는 저장된 전화번호의 갯수를 뜻한다.
92명의 이름을 String 배열에 넣고 뽑아봤는데 log.d에서는 아직 한글을 지원못하는가보다. =_=a 방법이 없을까나... 흠.
오른쪽 사진.
위 소스코드를 실행한 화면. 여기서 bottom부분에 확인 취소버튼을 고정시키는 커스텀어댑터를 만드는게 목적이었으나;
오늘은 여기까지만...
원본출처:http://canon110.tistory.com/66