检索Android联系人

时间:2011-11-18 17:21:15

标签: android contacts contactscontract

ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
    while (cur.moveToNext()) {
        String id = cur.getString(
        cur.getColumnIndex(ContactsContract.Contacts._ID));
        String name = cur.getString(
        cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

        if (name.equals(selected) && Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

            Cursor pCur = cr.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " =?", new String[] {
                id
            }, null);
            finalsend = ContactsContract.CommonDataKinds.Phone.NUMBER;
            while (pCur.moveToNext()) {

            }
            pCur.close();

        }

代码应该通过联系人来查找匹配“选定”变量的代码,该变量似乎工作正常但是它应该切换到ContactsContract.CommonDataKinds.Phone.CONTENT_URI并通过匹配ID来找到相同的联系人并告诉我为该联系人保存的电话号码。

每次返回“Data1”时,我做错了什么?这可能是一个愚蠢的错误,但任何帮助都表示赞赏。

1 个答案:

答案 0 :(得分:0)

以下代码段对我有用:

String id , name;
ContentResolver cr = getContentResolver();

     String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

     Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,  null, null, null, sortOrder);



      if (cur.getCount() > 0) {


            while (cur.moveToNext()) {



                id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));

                name = cur.getString( cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                Log.i(tag, "Id is "+ id+"\t Name is"+name);

            if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0){                      


                        Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,

                            null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);



                        while (pCur.moveToNext()) {


                // Do something with phones



                       int phNumber = pCur.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);

                       String phn = pCur.getString(phNumber);

                       Log.i("phn number",  phn);



                    } 

                    pCur.close();

                }

                }

    }