2025-02-09

 

1.最簡潔的方法

 

使用類

 

android.provider.ContactsContract.CommonDataKinds.Phone; 

代碼如下:

 

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});  

 然後就可以使用ListView顯示姓名和電話號碼瞭。

 

註意:

 

1.如果一個人有兩個電話,則分別顯示。

 

2.如果有兩個相同的人,也會分別顯示,不會顯示一個人的。

 

運行結果:

2.一般方法

 

 

   使用類

 

android.provider.ContactsContract.Contacts 

  代碼如下:

 

view plain

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(); 

得到名字和電話號碼,放入Map中,然後再鈄Map放入List中。

之後就可以使用ListView顯示名字和電話號碼:

 

部分代碼如下:

 

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);  

註意:

 

1.若一個姓名下有多個電話號碼,則隻顯示一個姓名,多個號碼。

 

2.若有多個同名的,還是顯示多個姓名。

 

結果截圖:

 

3.未解問題

 

 

很多人都會使用類android.provider.ContactsContract.PhoneLookup;但此類中沒有CONTENT_URI,隻有CONTENT_FILTER_URI,可以使用它根據電話號碼查詢,但還沒找到查詢所有聯系人的方法。

 

若哪位大蝦知道,請告知!

 

謝謝!

摘自 lengyueqiufeng的專欄

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *