一、《Android应用开发揭秘》代码的问题
在该书上,
int nameIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String contact = cursor.getString(nameIndex);
两句是可以读到联系人的名字的,而
//取得电话号码
int numberFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.NUMBER);
String number = cursor.getString(numberFieldColumnIndex);
会发生错误,因为2.0后,读取电话号码的API发生了改变
二、代码
1: /***********************************/
2: /*
3: *联系人的名字、电话号码的读取与显示
4: */
5: /***********************************/
6: package com.Joe.Android.Examples_03_02;
7:
8: import android.app.Activity;
9: import android.content.ContentResolver;
10: import android.database.Cursor;
11: import android.os.Bundle;
12: import android.provider.ContactsContract;
13: import android.provider.ContactsContract.PhoneLookup;
14: import android.widget.TextView;
15:
16: public class mainActivity extends Activity {
17: /** Called when the activity is first created. */
18: @Override
19: public void onCreate(Bundle savedInstanceState) {
20: TextView tv = new TextView(this);
21: String string = "";
22: super.onCreate(savedInstanceState);
23: //得到contentresolver对象
24: ContentResolver cr = getContentResolver();
25: //取得电话本中开始一项的光标,必须先moveToNext()
26: Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
27: while(cursor.moveToNext()){
28: //取得联系人的名字索引
29: int nameIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
30: String contact = cursor.getString(nameIndex);
31: string += (contact+":"+"/n");
32:
33: //取得联系人的ID索引值
34: String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
35: //查询该位联系人的电话号码,类似的可以查询email,photo
36: Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
37: ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
38: + contactId, null, null);//第一个参数是确定查询电话号,第三个参数是查询具体某个人的过滤值
39: //一个人可能有几个号码
40: while(phone.moveToNext()){
41: String strPhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
42: string += (strPhoneNumber+"/n");
43: }
44: phone.close();
45: }
46: cursor.close();
47: //设置显示内容
48: tv.setText(string);
49: //显示
50: setContentView(tv);
51: //setContentView(R.layout.main);
52: }
53: }
三、注意点
最后要在AndroidManifest.xml的application之外加上