内容提供者之读取手机联系人

来源:互联网 发布:ipad1软件下载专区 编辑:程序博客网 时间:2024/05/06 21:44

我今天给大家讲的是通过内容访问者读取到手机的联系人和电话号码,

先分析,我们要拿到联系人和电话号码是二组数据,所有我们可以使用SimpleAdapter适配器,让我们先来看看效果,



可以看到除了联系人和电话号码还有id,首先我们想要对手机系统的一些机密文件读取我们

必须拥有那个权限


读取手机联系人的权限

<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>   
接下来我们要拿到数据源,也就是联系人和电话号码和id
用list集合来装数据源
List<Map<String,String>> list=new ArrayList<Map<String, String>>();

获取内容提供者的uri,并且还有content协议,类似http协议

Uri uri=Uri.parse("content://com.android.contacts/raw_contacts");Cursor cursor=cr.query(uri,null,null,null,null);

拿到所有联系人的名字

while (cursor.moveToNext()){Map<String,String> map=new HashMap<String,String>();    int id=cursor.getInt(cursor.getColumnIndex("_id"));    String name=cursor.getString(cursor.getColumnIndex("display_name"));
   到了这一步有必要跟大家扯一下类型转换的问题了,可以看到我们的id是int类型的,那么

    在安卓里面是怎么转换类型的呢

               1 如何将字串 String 转换成整数 int?                 A. 有两个方法:                1). int i = Integer.parseInt([String]);     
                  或   i = Integer.parseInt([String],[int radix]);               2). int i = Integer.valueOf(my_str).intValue();                注: 字串转成 Double, Float, Long 的方法大同小异.            2 如何将整数 int 转换成字串 String ?                   A. 有叁种方法:                   1.) String s = String.valueOf(i);                  2.) String s = Integer.toString(i);                 3.) String s = "" + i;            注: Double, Float, Long 转成字串的方法大同小异.
         String pid=""+id;

map.put("id",pid);
map.put("name",name);

联系人我们已经拿到了,有人会疑问怎么不把电话号码也一起拿了呢?
那是因为手机数据库里联系人和电话号码是二张表,重复以上的代码
Uri uriData=Uri.parse("content://com.android.contacts/raw_contacts/"+id+"/data");Cursor cursorData=cr.query(uriData,null,null,null,null);while (cursorData.moveToNext()){
       注意下面这种方法虽然能拿到号码,但是会报空指针的错,别问为什么,等我研究下再说    //  int type=cursorData.getInt(cursorData.getColumnIndex("mimetype_id"));    String type=cursorData.getString(cursorData.getColumnIndex("mimetype"));        String data1=cursorData.getString(cursorData.getColumnIndex("data1")); 
          map.put("data1",data1);

有了数据源,那一切都简单了

SimpleAdapter simpleAdapter=new SimpleAdapter(        this,//上下文        lists,//数据源        R.layout.item,//布局文件        new String[]{"id","name","data1"},//数据从哪来        new int[]{R.id.tv_item1,R.id.tv_item2,R.id.tv_item3});//数据放到哪去//绑定适配器lv_main_1.setAdapter(simpleAdapter);

最后运行就ok啦








1 0
原创粉丝点击