Android从联系人列表中获取电话号码

时间:2016-11-29 09:14:22

标签: android android-contacts

我有这些代码基本上使用ListView来显示联系人列表中的名称,我想在点击每个单一名称时获取他们的电话号码:

final ContentResolver cr = getContentResolver();

final Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
myCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[] {ContactsContract.Contacts.DISPLAY_NAME}, new int[]{R.id.TVRow}, 0);
myPhoneList.setAdapter(myCursorAdapter);

myPhoneList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        c.moveToPosition(position);
        Toast.makeText(getApplicationContext(), c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)), Toast.LENGTH_SHORT).show();
    }
});

onItemClick方法中

    GetColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)

返回-1,因此我无法使用此方法获取电话号码。

我还尝试打印出游标c的所有列,并返回34列,但唯一与电话号码相关的列是HasPhoneNumber

那么问题在哪里,我该如何解决?谢谢!

更新版本,其中传递给构建String的{​​{1}}数组已更改:

myCursorAdapter

我想更新的代码会在ListView中显示电话号码,但我收到一条错误,说“列'data1'不存在”。

4 个答案:

答案 0 :(得分:3)

您可以使用以下代码在Recyclerview中获取联系人列表;

  List<ContactVO> contactVOList = new ArrayList();

  String[] projection = new String[]{ContactsContract.Contacts._ID, ContactsContract.Data.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.PHOTO_URI};
    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    List<ContactVO> userList = new ArrayList<>();

    String lastPhoneName = " ";
    if (phones.getCount() > 0) {
        while (phones.moveToNext()) {
            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            String contactId = phones.getString(phones.getColumnIndex(ContactsContract.Contacts._ID));
            String photoUri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
            if (!name.equalsIgnoreCase(lastPhoneName)) {
                lastPhoneName = name;
                ContactVO user = new ContactVO();
                user.setContactName(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
                user.setContactNumber(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
                userList.add(user);
                Log.d("getContactsList", name + "---" + phoneNumber + " -- " + contactId + " -- " + photoUri);
            }
        }
    }
    phones.close();

    AllContactsAdapter contactAdapter = new AllContactsAdapter(userList, getApplicationContext());
    rvContacts.setLayoutManager(new LinearLayoutManager(PhoneDirectoryActivity.this));
    rvContacts.setAdapter(contactAdapter);

ContactVO类文件下面;

public class ContactVO
{
private String ContactImage;
private String ContactName;
private String ContactNumber;

public String getContactImage() {
    return ContactImage;
}

public void setContactImage(String contactImage) {
    this.ContactImage = ContactImage;
}

public String getContactName() {
    return ContactName;
}

public void setContactName(String contactName) {
    ContactName = contactName;
}

public String getContactNumber() {
    return ContactNumber;
}

public void setContactNumber(String contactNumber) {
    ContactNumber = contactNumber;
}
}

下面是AllContactsAdapter文件

    public class AllContactsAdapter extends RecyclerView.Adapter<AllContactsAdapter.ContactViewHolder> {

    private List<ContactVO> contactVOList;
    private Context mContext;
    private SparseBooleanArray itemStateArray = new SparseBooleanArray();

    public AllContactsAdapter(List<ContactVO> contactVOList, Context mContext) {
        this.contactVOList = contactVOList;
        this.mContext = mContext;
    }

    @Override
    public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.single_contact_view, null);
        ContactViewHolder contactViewHolder = new ContactViewHolder(view);
        return contactViewHolder;
    }

    @Override
    public void onBindViewHolder(ContactViewHolder holder, int position) {
        ContactVO contactVO = contactVOList.get(position);
        holder.tvContactName.setText(contactVO.getContactName());
        holder.tvPhoneNumber.setText(contactVO.getContactNumber());

        holder.bind(position);

        holder.cbContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int adapterPosition = position;
                if (!itemStateArray.get(adapterPosition, false)) {
                    holder.cbContact.setChecked(true);
                    contactsList.add(holder.tvPhoneNumber.getText().toString());
                    itemStateArray.put(adapterPosition, true);
                } else {
                    holder.cbContact.setChecked(false);
                    itemStateArray.put(adapterPosition, false);
                    contactsList.remove(holder.tvPhoneNumber.getText().toString());
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return contactVOList.size();
    }

    public class ContactViewHolder extends RecyclerView.ViewHolder {

        ImageView ivContactImage;
        TextView tvContactName;
        TextView tvPhoneNumber;
        CheckBox cbContact;

        public ContactViewHolder(View itemView) {
            super(itemView);
            ivContactImage = itemView.findViewById(R.id.ivContactImage);
            tvContactName = itemView.findViewById(R.id.tvContactName);
            tvPhoneNumber = itemView.findViewById(R.id.tvPhoneNumber);
            cbContact = itemView.findViewById(R.id.cbContact);
        }
        void bind(int arg1) {
            // use the sparse boolean array to check
            if (!itemStateArray.get(arg1, false)) {
                cbContact.setChecked(false);
            } else {
                cbContact.setChecked(true);
            }
        }
    }
}

答案 1 :(得分:1)

ContactsContract Android API会在Data表中存储有关电话号码等联系人的数据,而不是Contacts表。

仔细阅读:https://developer.android.com/reference/android/provider/ContactsContract.html

更新 - 这是您的代码的固定版本(未经测试):

final ContentResolver cr = getContentResolver();
String[] projection = new String[] {Contacts.DISPLAY_NAME, Phone.NUMBER};
final Cursor c = cr.query(Data.CONTENT_URI, projection, null, null, null);
myCursorAdapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[] {Phone.NUMBER}, new int[]{R.id.TVRow}, 0);
myPhoneList.setAdapter(myCursorAdapter);

myPhoneList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        c.moveToPosition(position);
        Toast.makeText(getApplicationContext(), c.getString(1), Toast.LENGTH_SHORT).show();
    }
});

答案 2 :(得分:1)

首先在AndroidManifest.xml中添加此行以获取用户的权限。

<uses-permission android:name="android.permission.READ_CONTACTS"/>

实施联系按钮

        phoneContactsButtton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
            // The below two line is needed to open the contact list of  mobile
                Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(contactPickerIntent,1);

            }
        });

你必须覆盖onActivityResult(),它将写入onCreate()mehtod的外部 与此相似

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   }


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode){
        case 1 :
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();

                Cursor cur =  getContentResolver().query(contactData, null, null, null, null);
                if (cur.getCount() > 0) {// thats mean some resutl has been found
                    if(cur.moveToNext()) {
                        String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                        String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        Log.e("Names", name);

                        if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
                        {

                            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
                            while (phones.moveToNext()) {
                                String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                Log.e("Number", phoneNumber);
                            }
                            phones.close();
                        }

                    }
                }
                cur.close();
            }
            break;
    }

}

答案 3 :(得分:0)

它返回-1,因为您没有从DB请求列new String[] {ContactsContract.Contacts.DISPLAY_NAME}

ContactsContract.Contacts.DISPLAY_NAME

ContactsContract.CommonDataKinds.Phone.NUMBER}是您要求的唯一字段。

为了能够获得电话号码,首先需要将其包含在您希望从DB获取的列列表中:

new String [] {ContactsContract.Contacts.DISPLAY_NAME,getView

现在你必须覆盖适配器&#39; onItemClick,所以它将名称设置到列表行的textView中。之后, public class MainModelscs <T> where T :class { public StoreAudit StoreAudit { get; set; } public StoreQuestions StoreQuestions { get; set; } public List<string> StoreWindow { get; set; } public IPagedList<T> IndexList { get; set; } } 将按预期工作