마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

[주소록] 한사람당 여러번호 가지고 있는 경우 불러오는 방법....

0 추천
TextView text = (TextView) findViewById(R.id.text);
 
 
 
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,"display_name"); 
 
int ididx = cursor.getColumnIndex(ContactsContract.Contacts._ID);
int nameidx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
 
while (cursor.moveToNext()) {
    // 전화 번호는 서브 쿼리로 조사해야 함.
    String id = cursor.getString(ididx);
    Cursor cursor2 = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
 
    int numidx = cursor2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
    // 전화의 타입에 따라 여러 개가 존재한다.
    ArrayList<String> strList = new ArrayList<String>(); 
    while (cursor2.moveToNext()) {      // 들어온 num이 같으면 하나로 인식해야 한다.
        String num = cursor2.getString(numidx).replace("-", "");
        if(num.length() >= 2 && num.trim().substring(0,2).equalsIgnoreCase("01")){
            if(!strList.contains(num)){
                strList.add(num);
                text.append(cursor.getString(nameidx)+" : "+strList.get(strList.size()-1)); 
                text.append("\n");
            }
        }
    }
    cursor2.close();
 
}
cursor.close();
 
 
현재 이렇게 코딩을 한 상태입니다.
 
그런데 친구가 별로 없으면 괜찮은데,
 
친구가 많으면 너무 느려지더라구요.
 
while문이 두개라서그런가....
 
어떻게 하는게 좋을까요 ㅠ?
 
다른방법으로 가져올수 있는 방법이 있다면 알려주세요~!!
 
말로설명하면 이해를 못하거둔요 ㅠㅠ..
 
혹시 소스 갖고계시거나 링크알고 계시면 공유해주셨음해용...ㅎ
 
슈퍼꽃붕어 (1,600 포인트) 님이 2014년 7월 4일 질문

1개의 답변

0 추천
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(Contacts.CONTENT_URI, new String[] {
                Contacts._ID
        }, null, null, Contacts._ID + " ASC");

        int contactCount = cursor.getCount();
        
        if (contactCount > 0) {
            StringBuilder idList = new StringBuilder();
            
            while (cursor.moveToNext()) {
                idList.append(cursor.getInt(0));
                if (!cursor.isLast()) {
                    idList.append(", ");    
                } else {
                    idList.append(")");
                }
            }
            String where = Phone.CONTACT_ID + " in (" + idList.toString();

            Cursor numberCursor = resolver.query(Phone.CONTENT_URI, new String[] {
                Phone._ID, Phone.CONTACT_ID, Phone.NUMBER
                }, where, null, Phone.CONTACT_ID + " ASC");

            while (numberCursor.moveToNext()) {
                ...
            }
        }
        cursor.close();

100% 완성한 코드는 아닙니다.

느린 이유는 불필요하게 while 문 안에서 또 while 을 돌아야 하는 것 때문인데요.

위에 고친것처럼 독립적으로 while 문을 돌면 좀 덜 느릴꺼에요. 그래도 느리긴 하겠지만.

SQL query 문에서 where 절에는 in 을 사용해서 한번에 검색 해보세요.

카라드레스 (2,910 포인트) 님이 2014년 7월 4일 답변
...