为什么我无法接通手机上的所有联系人?

时间:2016-11-17 05:25:42

标签: android

我写了一个代码,它返回了我手机上的所有联系人。 但当我在我的Android手机上运行时,我看到即使我有600个联系人 - 我的代码只有173个联系人

如何获得所有联系人? 为什么我只得到其中的173个?

代码:

 private void CollectAllContacts(Activity activity){
        ArrayList<ContactData> contactDataList = new ArrayList<ContactData>();


    try {

        ContentResolver cr = activity.getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                ContactData newContact = new ContactData();

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

                newContact.setId(id);
                newContact.setDisplayName(name);

                contactDataList.add(newContact);
            }
        }
    }
    catch(Exception e)
    {
             // write to log. 
    }
}

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题。我通过使用意图来解决它。你可以试试这个

 Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
            pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
            startActivityForResult(pickContactIntent, 100);

然后onActivityResult你可以处理它

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 100 && resultCode == getActivity().RESULT_OK && null != data) {
        Uri uri = data.getData();
        String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER};

        Cursor people = getActivity().getContentResolver().query(uri, projection, null, null, null);
        int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

        people.moveToFirst();
        do {
            String phoneNumber = people.getString(indexNumber);
            phoneNumber = phoneNumber.replaceAll("[-]", "").replaceAll(" ", "");


        } while (people.moveToNext());

    }
}