显示联系人姓名无效

Displaying contact name not working

下面提到的代码在 Logcat

上没有显示任何名称
Cursor cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
            null, null, null, null);

    while(cursor.moveToNext()) {
        name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        Log.d("name : ", ""+name);
    }

    cursor.close();

根据上面的代码,我试图在 Logcat 上显示联系人姓名。但是 while 循环没有执行。我的代码有没有错误。

如何解决?

在 while 循环中执行 cursor.moveToFirst()。当你检查 cursor.moveToNext() 时,光标将移动到下一个位置,那里的数据将为空。所以你应该将光标移动到第一个位置 n 然后打印名称。

希望对您有所帮助:)

Cursor phones = cr.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
                null, null);
        while (phones.moveToNext()) {
            ContactSynRequestcontacts data = new ContactSynRequestcontacts();
            String name = phones
                    .getString(phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones
                    .getString(phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            data.setName(name);
            data.setPhoneNumber(phoneNumber);
            userContactList.add(data);
        }
        phones.close();// close cursor

You also need to add premission 
    <uses-permission android:name="android.permission.READ_CONTACTS" />
in manifest.