Introduction To Android Contacts
Learn to work with the Android contacts database. Basic knowledge of accessing SQLite in Android along with using Cursors is expected. See the Android SQLite and Cursor Article for more information. Google changed the contacts database moving from 1.x to 2.0 versions of Android. This tutorial will be broken into 3 sections. First covering accessing contacts in Android 2.0. The second page will deal with accessing the contacts in Android 1.6 and before. Third we'll glue it all together with a class that abstracts specific classes for each version and a set of classes to manage the data from the contact records.
Contacts 讀取代碼:
package com.homer.phone;</p><p>import java.util.ArrayList;<br />import java.util.HashMap;</p><p>import android.app.Activity;<br />import android.database.Cursor;<br />import android.os.Bundle;<br />import android.provider.ContactsContract;<br />import android.provider.ContactsContract.CommonDataKinds.Phone;<br />import android.widget.ListView;<br />import android.widget.SimpleAdapter;</p><p>public class phoneRead extends Activity {</p><p>@Override<br />public void onCreate(Bundle savedInstanceState){<br />super.onCreate(savedInstanceState);</p><p>showListView();<br />}</p><p>private void showListView(){<br />ListView listView = new ListView(this);</p><p>ArrayList<HashMap<String, String>> list = getPeopleInPhone2();<br />SimpleAdapter adapter = new SimpleAdapter(<br />this,<br />list,<br />android.R.layout.simple_list_item_2,<br />new String[] {"peopleName", "phoneNum"},<br />new int[]{android.R.id.text1, android.R.id.text2}<br />);<br />listView.setAdapter(adapter);</p><p>setContentView(listView);<br />}</p><p>private ArrayList<HashMap<String, String>> getPeopleInPhone2(){<br />ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();</p><p> Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);// 擷取手機連絡人<br />while (cursor.moveToNext()) {<br />HashMap<String, String> map = new HashMap<String, String>();</p><p>int indexPeopleName = cursor.getColumnIndex(Phone.DISPLAY_NAME); // people name<br />int indexPhoneNum = cursor.getColumnIndex(Phone.NUMBER); // phone number</p><p>String strPeopleName = cursor.getString(indexPeopleName);<br />String strPhoneNum = cursor.getString(indexPhoneNum);</p><p>map.put("peopleName", strPeopleName);<br />map.put("phoneNum", strPhoneNum);<br />list.add(map);<br />}<br /> if(!cursor.isClosed()){<br /> cursor.close();<br /> cursor = null;<br /> }</p><p> return list;<br />}<br />}
AndroidManifest.xml 許可權
記得在AndroidManifest.xml中加入android.permission.READ_CONTACTS這個permission
<uses-permission android:name="android.permission.READ_CONTACTS" />
運行結果:
程式碼範例
參考推薦:
Working With Android Contacts
Android Contacts的使用