Android中获取联系人的名字和号码

讲到获取Contacts的名字和号码,首先给大家简单介绍一下两个类ContentProvider和ContentResolver。一般我们都用ContentResolver类中的一些方法来处理ContentProvider暴露出来的数据,在Contacts方面这些数据主要有CONTENT_URI(管理联系人的uri),Phone.CONTENT_URI(管理联系人电话的uri),Email.CONTENT_URI(管理联系人email的uri)。使用ContentResolver来操作这些数据只要两步:第一,调用Activity的getContentResolver()来获取ContentResolver对象。

第二,根据需要调用ContentResolver中的insert(),delete(),update(),query()方法操作数据即可。

调用:

ContentResolver cr = AddGesture.this.getContentResolver();

操作数据,以query为例:

Cursor cursor = getContentResolver().query(
     ContactsContract.Contacts.CONTENT_URI
     , null, null, null, null);    
    // 遍历查询结果,获取系统中所有联系人
    while (cursor.moveToNext())
    {
     // 获取联系人ID
     String contactId = cursor.getString(cursor
      .getColumnIndex(ContactsContract.Contacts._ID));
     // 获取联系人的名字
     String name = cursor.getString(cursor
      .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
     names.add(name);
     // 使用ContentResolver查找联系人的电话号码
     Cursor phones = getContentResolver().query(
      ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
      null,
      ContactsContract.CommonDataKinds.Phone.CONTACT_ID
       + " = " + contactId, null, null);
     ArrayList<String> detail = new ArrayList<String>();
     // 遍历查询结果,获取该联系人的多个电话号码
     while (phones.moveToNext())
     {
      // 获取查询结果中电话号码列中数据。
      String phoneNumber = phones
       .getString(phones
       .getColumnIndex(ContactsContract
       .CommonDataKinds.Phone.NUMBER));
      detail.add("电话号码:" + phoneNumber);
     }
     phones.close();

也可以通过联系人的名字来查找号码,只要更改query()方法中的参数即可:

Cursor android.content.ContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)

改变第三和第四个参数:

String[] projection = new String[]
     {ContactsContract.CommonDataKinds.Phone.NUMBER};
   
   cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
     ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + "=?", new String[]{name}, "");

第四个参数就是所要搜索的名字,projection是A list of which columns to return. Passing null will return all columns, which is inefficient.返回的数据列表,本代码只返回电话号码,如果将其设置为null,则返回所有的列表,这个效率不高,所以一般都会设置。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值