練習代碼 3-2 《安卓應用開發揭秘》

來源:互聯網
上載者:User
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);
        while(cursor.moveToNext())
        { 
            try{
                int idColumn  = cursor.getColumnIndex(ContactsContract.Contacts._ID); 
                String contactId = cursor.getString(idColumn);   
                //取得連絡人名字
                int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
                String contact = cursor.getString(nameFieldColumnIndex); 
                //取得電話號碼
                String phoneNumber = ""; 
                //取得該連絡人,電話數量
                int phoneCount = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));   
                if(phoneCount>0){   
                    //獲得連絡人的電話號碼   
                    Cursor phones = getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = " + contactId,
                            null, null);   
                    if(phones.moveToFirst()){
                        do{   
                            //遍曆所有的電話號碼   
                            phoneNumber += phones.getString(phones.getColumnIndex(
                                    ContactsContract.CommonDataKinds.Phone.NUMBER)) + "\t";   
                            System.out.println(phoneNumber);   
                        }while(phones.moveToNext());   
                    }
                }
                string += contact + ":" + phoneNumber +"\n";
            }catch(Exception ex){
                ex.printStackTrace();
            }
            
            //cursor.moveToNext();
        }
        cursor.close();
        //設定TextView顯示的內容
        tv.setText(string);
        //顯示到螢幕
        setContentView(tv);
    }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.