首页 > 解决方案 > 获取联系人错误 - 如何解决?

问题描述

我的问题是我列出了联系人,电话号码显示得很好,但是我无法让这些名字正常工作。

我尝试了几种方法来获得“DISPLAY_NAME”,但没有一种方法奏效

    private void initializeRecyclerView() {
        mUserList = findViewById(R.id.userList);
        mUserList.setNestedScrollingEnabled(false);
        mUserList.setHasFixedSize(false);
        mUserListLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayout.VERTICAL, false);
        mUserList.setLayoutManager(mUserListLayoutManager);
        mUserListAdapter = new UserListAdapter(userList);
        mUserList.setAdapter(mUserListAdapter);
        getContactsList();
    }

This is my adaptor ^^

    private void getContactsList(){
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        while(phones.moveToNext()){
            String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

            UserObject mContact = new UserObject(name, phone);
            userList.add(mContact);
            mUserListAdapter.notifyDataSetChanged();
        }
    }

标签: javaandroidcontacts

解决方案


您需要添加PROJECTION

您可以将此方法放入您的代码中

 public Cursor getContact(Context context) {
        String[] PROJECTION = new String[]{
                ContactsContract.RawContacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER
               };
        Uri uri = CommonDataKinds.Phone.CONTENT_URI;

        String order = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";// LIMIT " + limit + " offset " + lastId + "";
        try {
            return context.getContentResolver().query(uri, PROJECTION, null, null, order);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

并使用

ContactsContract.Contacts.DISPLAY_NAME

快乐编码


推荐阅读