当光标包含所有联系人时,联系人姓名将为空

时间:2018-01-24 15:29:38

标签: android android-contacts

  

我在这段代码中得到'name = null',而游标中包含了我所有的联系人,我尝试了很多不同的方法,但它们都做了同样的事情。

String[] contact_names, mobile_numbers;

Cursor cursor = getActivity().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);

        while (cursor.moveToFirst()) {

            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

            contact_names[contact_names.length] = name;

            Cursor phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?" + contactId, null, null);
            while (phones.moveToNext()) {
                String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                mobile_numbers[mobile_numbers.length] = number;
            }
            phones.close();
        }
        cursor.close();

1 个答案:

答案 0 :(得分:1)

您不需要多次查询,请使用以下内容在一个查询中完成所有操作,

String[] PROJECTION_MAIN = new String[]{
                ContactsContract.Contacts._ID,
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.Contacts.DISPLAY_NAME
        };

Cursor cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    PROJECTION_MAIN, null, null, null);

while (cursor.moveToNext()) {
                    String contact_id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    String phone = cleanNumber(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)), context);

}