在android中获取联系人的号码和姓名

时间:2013-08-13 05:07:38

标签: android android-contacts

我正在获取所有联系人姓名和号码bur我只想显示我选择的号码和名称。

这是返回所有联系人的代码:

ArrayList<String> contactList = new ArrayList<String>();

    switch (reqCode) {
    case (0):
        if (resultCode == Activity.RESULT_OK) {

            Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            String[] projection = new String[] {
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER };

            Cursor people = getContentResolver().query(uri, projection,
                    null, null, null);

            int indexName = people
                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
            int indexNumber = people
                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

            people.moveToFirst();
            do {
                String name = people.getString(indexName);
                String number = people.getString(indexNumber);

                String contact = name + "" + number;
                contactList.add(contact);
            } while (people.moveToNext());

        }
contactList中的

我想添加一个数字和一个名字

1 个答案:

答案 0 :(得分:1)

据我了解你的问题,你想在集合中添加数字和名称 - 使用HashMap。

 HashMap<String,String> contactList = new HashMap<String,String>();

switch (reqCode) {
case (0):
    if (resultCode == Activity.RESULT_OK) {

        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] projection = new String[] {
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER };

        Cursor people = getContentResolver().query(uri, projection,
                null, null, null);

        int indexName = people
                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
        int indexNumber = people
                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

        people.moveToFirst();
        do {
            String name = people.getString(indexName);
            String number = people.getString(indexNumber);

            String contact = name + "" + number;
            contactList.put(number,name);
        } while (people.moveToNext());

    }