Android中读取电话本Contacts联系人的所有电话号信息

1.首先,要知道android 的contacts里的电话信息有多类:moblie,家庭,工作,传真等。如图:

Android中读取电话本Contacts联系人的所有电话号信息_第1张图片

 

2.android的Contacts是通过ContentProvider来提供的,其实android把contacts和SMS给组织成数据库文件了,你可以在File Explorer 的/data/data/com.android.provider.contacts下找到contacts.db,这就是电话本数据库文件,你手机里的contacts信息都在这个数据库的各张表里。

Android中读取电话本Contacts联系人的所有电话号信息_第2张图片

 

3.知道contacts信息是在一个数据库里就要知道这张数据库里的都有什么表,这些表的字段都有什么。我们可以把这个contacts.db文件提取出来,再用SQLite Expert Professional 2这个软件打开,就可以看到数据库的信息了。如图:

Android中读取电话本Contacts联系人的所有电话号信息_第3张图片

 

4.可以看出和API说的一样,people和phones都是一张表,注意下phones这张表,这里就有我们要的所有电话号码信息。也可以看到以下两点:

    4.1:phones表中的person字段对应为people表中的_id;

    4.2:  phones表中的type字段就是API中Contacts.PhonesColumns的TYPE字段,这个就是电话的7个分类,TYPE=2为moblie

 

5.这样就可以用代码来提取出来数据了,要注意一点,在用query()查找时的Uri直接指向phones表就OK。

Cursor contactcursor = content.query(Contacts.Phones.CONTENT_URI, null,null, null, Contacts.People.DEFAULT_SORT_ORDER);

 

6.下面是一个完整的方法代码:

/* 读取手机中的contacts内容 */private void getContactsInfoListFromPhone() {/* 取得ContentResolver */ContentResolver content = this.getContentResolver();/* 取得通讯录的Phones表的cursor */Cursor contactcursor = content.query(Contacts.Phones.CONTENT_URI, null,null, null, Contacts.People.DEFAULT_SORT_ORDER);/* 在LogCat里打印所有关于的列名 */for (int i = 0; i < contactcursor.getColumnCount(); i++) {String columnName = contactcursor.getColumnName(i);Log.d("readTXT", "column name:" + columnName);}/* 逐条读取记录信息 */int Num = contactcursor.getCount();Log.v("readTXT", "recNum=" + Num);String name, number;for (int i = 0; i < Num; i++) {contactcursor.moveToPosition(i);String type = contactcursor.getString(contactcursor.getColumnIndexOrThrow(Contacts.Phones.TYPE));Log.v("readTXT", "type=" + type);String person_id = contactcursor.getString(contactcursor.getColumnIndexOrThrow(Contacts.Phones.PERSON_ID));Log.v("readTXT", "person_id=" + person_id);name = contactcursor.getString(contactcursor.getColumnIndexOrThrow(Contacts.Phones.NAME));number = contactcursor.getString(contactcursor.getColumnIndexOrThrow(Contacts.Phones.NUMBER));// number = number == null ? "无输入电话" : number;// 当找不到电话时显示"无输入电话"nameContactsInPhone.add(name);Log.v("readTXT", "name=" + name);numberContactsInPhone.add(number);Log.v("readTXT", "*****number=" + number);}}

 

7.从上面的代码可以总结一点经验,在不知道数据库表的字段时,可以用下面的方法来打印出来,就可以清楚后,再应用了:

/* 取得通讯录的Phones表的cursor */Cursor contactcursor = content.query(Contacts.Phones.CONTENT_URI, null,null, null, Contacts.People.DEFAULT_SORT_ORDER);/* 在LogCat里打印所有关于的列名 */for (int i = 0; i < contactcursor.getColumnCount(); i++) {String columnName = contactcursor.getColumnName(i);Log.d("readTXT", "column name:" + columnName);}

 

你可能感兴趣的:(数据库,android,String,sqlite,null,电话)