程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> cursor-如何獲取聯系人的電話號碼?

cursor-如何獲取聯系人的電話號碼?

編輯:編程綜合問答
如何獲取聯系人的電話號碼?

代碼如下:

String[] columns = {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER};
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, columns, null, null, null);
int ColumeIndex_ID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
int ColumeIndex_DISPLAY_NAME = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int ColumeIndex_HAS_PHONE_NUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
while(cursor.moveToNext()) 
{   
    String id = cursor.getString(ColumeIndex_ID);
    String name = cursor.getString(ColumeIndex_DISPLAY_NAME);
    String has_phone = cursor.getString(ColumeIndex_HAS_PHONE_NUMBER);
    if(!has_phone.endsWith("0")) 
    {
        System.out.println(name);
        GetPhoneNumber(id);
    }           
}
 cursor.close();
public String GetPhoneNumber(String id) 
{
    String number = "";
    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone._ID + " = " + id, null, null);
     if(phones.getCount() > 0) 
    {
        while(phones.moveToNext()) 
        {
            number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        }
        System.out.println(number);
    }
    phones.close();
    return number;
}

我能獲取聯系人的姓名,但是不能在GetPhoneNumber()中獲取電話號碼。
phones.getCount() 總是等於0,如何修改?

最佳回答:


Android Contact API 2.0

ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
    "DISPLAY_NAME = '" + NAME + "'", null, null);
if (cursor.moveToFirst()) {
    String contactId =
        cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
    //
    //  Get all phone numbers.
    //
    Cursor phones = cr.query(Phone.CONTENT_URI, null,
        Phone.CONTACT_ID + " = " + contactId, null, null);
    while (phones.moveToNext()) {
        String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
        int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
        switch (type) {
            case Phone.TYPE_HOME:
                // do something with the Home number here...
                break;
            case Phone.TYPE_MOBILE:
                // do something with the Mobile number here...
                break;
            case Phone.TYPE_WORK:
                // do something with the Work number here...
                break;
            }
    }
    phones.close();
 }

cursor.close();

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved