最近開始學習Android,主要看的是《Android應用開發揭秘》,在第3章的Example_03_02是一個讀取通訊錄連絡人姓名和電話的執行個體,但由於API 2.0中,每個連絡人可以有多個電話(例如手機、住宅、公司、傳真等),書中原有的執行個體在API 2.0的環境中會報錯。
書中的Example_03_02代碼:
View Code
package com.yarin.android.Examples_03_02;import android.app.Activity;import android.content.ContentResolver;import android.database.Cursor;import android.os.Bundle;import android.provider.ContactsContract;import android.provider.ContactsContract.PhoneLookup;import android.util.Log;import android.widget.TextView;import org.apache.commons.lang.StringUtils;public class Activity01 extends Activity{ public void onCreate(Bundle savedInstanceState) { TextView tv = new TextView(this); String string = ""; super.onCreate(savedInstanceState); //得到ContentResolver對象 ContentResolver cr = getContentResolver(); //取得電話本中開始一項的游標 Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); Log.i("tag",Integer.toString(cursor.getColumnCount())) ; Log.i("tag",StringUtils.join(cursor.getColumnNames(), ",") ) ; //向下移動一下游標 while(cursor.moveToNext()) { //取得連絡人名字 int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME); String contact = cursor.getString(nameFieldColumnIndex); //取得電話號碼 (此方法會報錯,因為一個連絡人可能有多個聯絡電話) //int numberFieldColumnIndex = cursor.getColumnIndex(PhoneLookup._ID); //String number = cursor.getString(numberFieldColumnIndex); //string += (contact+":"+number+"\n"); //新方法擷取電話號碼 String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +"="+ ContactId, null, null); while(phone.moveToNext()) { String PhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); string += (contact +":"+ PhoneNumber +"\n"); } } cursor.close(); //設定TextView顯示的內容 tv.setText(string); //顯示到螢幕 setContentView(tv); }}
其中的原代碼已被我註解,並改了正確的代碼
如果我們只想擷取手機號如何操作呢?
Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
把以上語句改為:
Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId + " AND " + ContactsContract.CommonDataKinds.Phone.TYPE + "=" + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE, null, null);
ContactsContract.CommonDataKinds.Phone.TYPE 表示連絡人電話的類型,主要對應如下:
TYPE_MOBILE : 手機號碼
TYPE_HOME : 住家電話
TYPE_WORK : 公司電話
最後附加main.xml的代碼
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /></LinearLayout>