如何检索android中的联系人列表

时间:2013-04-20 19:01:23

标签: android json contacts

我检索联系人列表(名称,号码)的目的是记录在json对象中,通过Web服务发送到服务器

然后我找到了访问联系人的代码,这很好,我测试了这段代码

String id, name;

        ContentResolver crs = getContentResolver();

        Cursor people = crs.query(ContactsContract.Contacts.CONTENT_URI, null,
                null, null, null);



        String phone = "";

        people.moveToPosition(Contexts.getnbContacts());

        while (people.moveToNext())

        {

            id = people.getString(people
                    .getColumnIndex(ContactsContract.Data._ID));
            name = people.getString(people
                    .getColumnIndex(ContactsContract.Data.DISPLAY_NAME));

            if (Integer
                    .parseInt(people.getString(people
                            .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

                Cursor phones = getContentResolver().query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                + " = " + id, null, null);
                while (phones.moveToNext()) {
                    // pdata =
                    // phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
                    phone = phone
                            + phones.getString(phones
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA))
                            + " and ";
                    ;
                }

                phones.close();

            }

我的问题是:如何在数组或arraylist中保存每个联系人(姓名,号码)......

每个表格行指定联系人

我认为数组类型与json格式兼容

所以如何复制json对象中的联系人

2 个答案:

答案 0 :(得分:4)

这里是我的代码

public static Map<String, String> getAddressBook(Context context)
{
    Map<String, String> result = new HashMap<String, String>();
    Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
    while(cursor.moveToNext()) 
    {
        int phone_idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
        int name_idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
        String phone = cursor.getString(phone_idx);
        String name = cursor.getString(name_idx);
        result.put(name, phone);
    }
    cursor.close();

    return result;
}

并且需要

<uses-permission android:name="android.permission.READ_CONTACTS"/>

答案 1 :(得分:0)

您可以使用以下查询从“联系人数据库”中检索收藏的联系人

Cursor cursor = this.managedQuery(ContactsContract.Contacts.CONTENT_URI, projection, "starred=?",new String[] {"1"}, null);