標籤:android style blog http ar os 使用 java sp
1.最簡潔的方法
使用類
android.provider.ContactsContract.CommonDataKinds.Phone;
代碼如下:
<span style="font-size:18px;"> Cursor c = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null,null); startManagingCursor(c); ListAdapter adapter=new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, c, new String[]{Phone.DISPLAY_NAME,Phone.NUMBER}, new int[]{android.R.id.text1,android.R.id.text2}); </span>
然後就可以使用ListView顯示姓名和電話號碼了。
注意:
1.如果一個人有兩個電話,則分別顯示。
2.如果有兩個相同的人,也會分別顯示,不會顯示一個人的。
運行結果:
2.一般方法
使用類
<span style="font-size:18px;">android.provider.ContactsContract.Contacts </span>
代碼如下:
<span style="font-size:18px;">Map<String,String> contacts; List<Map<String,String>> list=new ArrayList<Map<String,String>>(); int nameIndex=-1; ContentResolver cr=getContentResolver(); Cursor cur=cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null,null); while(cur.moveToNext()){ number=""; //得到名字 nameIndex=cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); name=cur.getString(nameIndex); //得到電話號碼 String contactId = cur.getString(cur .getColumnIndex(ContactsContract.Contacts._ID)); // 擷取連絡人的ID號,在SQLite中的資料庫ID Cursor phone = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null); while (phone.moveToNext()) { String strPhoneNumber = phone.getString( phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); // 手機號碼欄位連絡人可能不止一個 number += strPhoneNumber+"\n"; } contacts=new HashMap<String,String>(); //放入Map contacts.put("name", name); contacts.put("number", number); list.add(contacts); } cur.close(); </span>
得到名字和電話號碼,放入Map中,然後再鈄Map放入List中。
之後就可以使用ListView顯示名字和電話號碼:
部分代碼如下:
<span style="font-size:18px;">SimpleAdapter adapter = new SimpleAdapter(this,list,android.R.layout.simple_list_item_2, new String[]{"name","number"}, new int[]{android.R.id.text1,android.R.id.text2}); listView.setAdapter(adapter); </span>
注意:
1.若一個姓名下有多個電話號碼,則只顯示一個姓名,多個號碼。
2.若有多個同名的,還是顯示多個姓名。
結果:
擷取手機通訊錄資訊方法總結