显示联系人姓名不起作用

时间:2015-06-24 09:19:49

标签: android android-contacts

下面提到的代码在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循环没有执行。我的编码是否有任何错误。

如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

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

希望这会有所帮助:)

答案 1 :(得分:1)

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.