Android 获取联系人列表

import android.app.ListActivity;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;

/**
 *
 * data comes from a cursor.
 */
@SuppressWarnings("deprecation")
public class ContactList extends ListActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Get a cursor with all people
        Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI ,null, null, null, null);
        startManagingCursor(c);

        ListAdapter adapter = new SimpleCursorAdapter(this, 
                // Use a template that displays a text view
                android.R.layout.simple_list_item_1, 
                // Give the cursor to the list adatper
                c, 
                // Map the NAME column in the people database to...
                new String[] {PhoneLookup.DISPLAY_NAME} ,
                // The "text1" view defined in the XML template
                new int[] {android.R.id.text1}); 
        setListAdapter(adapter);
    }
}


//
Andorid1.5及其以前的项目放到Android2.0上时,如果代码中有
import android.provider.Contacts;  
Eclipse会提示“建议不使用”,那是因为在Android2.0中,联系人api发生了变化,需要使用ContactsContract。
直接看下面一个最简单的例子,读取联系人的姓名和电话号码:
读取联系人的名字很简单,但是在读取电话号码时,就需要先去的联系人的ID,然后在通过ID去查找电话号码!一个联系人可能存在多个电话号码!

//得到ContentResolver对象   
ContentResolver cr = getContentResolver();     
//取得电话本中开始一项的光标   
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);   
while (cursor.moveToNext())   
{   
    // 取得联系人名字   
   int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);   
    String name = cursor.getString(nameFieldColumnIndex);   
    string += (name);   
    // 取得联系人ID   
    String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._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));   
        string += (":" + strPhoneNumber);   
    }   
    string += "\n";   
    phone.close();   
}   
cursor.close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值