本文介绍了如何在不重复的情况下获取所有联系人的名字、姓氏、电子邮件、电话号码等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码获取电话联系人中所有可用联系人的详细信息.但面临重复值的小问题.

已编辑

实际代码开始:-

private String refreshData() {String emaildata = "";尝试 {ContentResolver cr = getBaseContext().getContentResolver();字符串选择 = ContactsContract.Contacts.IN_VISIBLE_GROUP+ " = '" + ("1") + "'";String sortOrder = ContactsContract.Contacts.DISPLAY_NAME+整理本地化的ASC";光标cur = cr.query(ContactsContract.Contacts.CONTENT_URI,空值,选择+ " 与 "+ ContactsContract.Contacts.HAS_PHONE_NUMBER+ "=1", null, sortOrder);如果(cur.getCount()> 0){Log.i("内容提供商", "阅读联系邮件");而(cur.moveToNext()){mContactSet.add(cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID)));}} 别的 {emaildata += "未找到数据.";}cur.close();Log.i(TAG, "联系人总数 = " + mContactSet.size());迭代器迭代器 = mContactSet.iterator();而(迭代器.hasNext()){String contactId = iterator.next();Log.i(TAG, "ID ==> " + contactId);//创建查询以使用 CommonDataKinds 类来获取//电子邮件光标电子邮件 = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID+ " = " + contactId, null, null);//姓名String whereName = ContactsContract.Data.MIMETYPE+ " = ? AND "+ ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID+ " = ?";String[] whereNameParams = new String[] {ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,联系人 ID };光标名称Cur = cr.query(ContactsContract.Data.CONTENT_URI,空值,哪里名字,whereNameParams,ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);而 (nameCur.moveToNext()) {给定的字符串 = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));字符串系列 = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));字符串显示 = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));Log.i(TAG, "名字 ==> " + 给定);Log.i(TAG, "Last Name ==> " + family);Log.i(TAG, "Display ==> " + display);}nameCur.close();}} 捕获(异常 e){emaildata += "异常:" + e + "";}返回电子邮件数据;}

修改了查询并获得了一些更好的结果,但对于某些联系人和获取重复值仍然存在相同的问题.

UPDATE :- 我已经使用 HashSet 来获取唯一的联系人 id 并且我也成功地获得了它,但是当我从联系人 id 中获取姓名时,我得到了 2-3 次相同的值联系人.我很困惑,同一个联系人用同一个 id 存储 2-3 次怎么可能?

我是否需要对名字、姓氏、电话号码、电子邮件等使用哈希集?还有其他方法吗?

解决方案

这是完整的解决方案

public ArrayList>获取联系人(){ArrayList>联系人 = 新的 ArrayList>();final String[] 投影 = new String[] { RawContacts.CONTACT_ID, RawContacts.DELETED };@SuppressWarnings("弃用")final Cursor rawContacts = managedQuery(RawContacts.CONTENT_URI,projection,null,null,null);最终 int contactIdColumnIndex = rawContacts.getColumnIndex(RawContacts.CONTACT_ID);最终 int 删除列索引 = rawContacts.getColumnIndex(RawContacts.DELETED);如果(rawContacts.moveToFirst()){while (!rawContacts.isAfterLast()) {最终 int contactId = rawContacts.getInt(contactIdColumnIndex);最终布尔删除 = (rawContacts.getInt(deletedColumnIndex) == 1);如果(!删除){HashMapcontactInfo = new HashMap() {{put("contactId", "");把(名称",");put("email", "");put("地址", "");把(照片",");把(电话",");}};contactInfo.put("contactId", "" + contactId);contactInfo.put("name", getName(contactId));contactInfo.put("email", getEmail(contactId));contactInfo.put("photo", getPhoto(contactId) != null ? getPhoto(contactId) : "");contactInfo.put("address", getAddress(contactId));contactInfo.put("phone", getPhoneNumber(contactId));contactInfo.put("isChecked", "false");联系人.添加(联系人信息);}rawContacts.moveToNext();}}rawContacts.close();返回联系人;}私人字符串 getName(int contactId) {字符串名称 = "";final String[] 投影 = new String[] { Contacts.DISPLAY_NAME };final Cursor contact = managedQuery(Contacts.CONTENT_URI,projection, Contacts._ID + "=?", new String[] { String.valueOf(contactId) }, null);如果(contact.moveToFirst()){name = contact.getString(contact.getColumnIndex(Contacts.DISPLAY_NAME));contact.close();}contact.close();返回名称;}私人字符串 getEmail(int contactId) {String emailStr = "";final String[]projection = new String[] { Email.DATA,//使用//电子邮件地址//对于 API 级别//11+电子邮件.TYPE };final Cursor email = managedQuery(Email.CONTENT_URI,projection, Data.CONTACT_ID + "=?", new String[] { String.valueOf(contactId) }, null);如果(email.moveToFirst()){final int contactEmailColumnIndex = email.getColumnIndex(Email.DATA);而 (!email.isAfterLast()) {emailStr = emailStr + email.getString(contactEmailColumnIndex) + ";";email.moveToNext();}}电子邮件.关闭();返回 emailStr;}私人位图 getPhoto(int contactId) {位图照片 = null;final String[] 投影 = new String[] { Contacts.PHOTO_ID };final Cursor contact = managedQuery(Contacts.CONTENT_URI,projection, Contacts._ID + "=?", new String[] { String.valueOf(contactId) }, null);如果(contact.moveToFirst()){final String photoId = contact.getString(contact.getColumnIndex(Contacts.PHOTO_ID));如果(照片ID!= null){照片 = getBitmap(photoId);} 别的 {照片 = 空;}}contact.close();返回照片;}私有位图 getBitmap(String photoId) {final Cursor photo = managedQuery(Data.CONTENT_URI, new String[] { Photo.PHOTO }, Data._ID + "=?", new String[] { photoId }, null);最终位图 photoBitmap;如果(照片.moveToFirst()){字节[] photoBlob = photo.getBlob(photo.getColumnIndex(Photo.PHOTO));photoBitmap = BitmapFactory.decodeByteArray(photoBlob, 0, photoBlob.length);} 别的 {photoBitmap = null;}照片.关闭();返回照片位图;}私人字符串 getAddress(int contactId) {String postalData = "";String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";String[] addrWhereParams = new String[] { String.valueOf(contactId), ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };Cursor addrCur = managedQuery(ContactsContract.Data.CONTENT_URI, null, addrWhere, addrWhereParams, null);如果(addrCur.moveToFirst()){postalData = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));}addrCur.close();返回邮政数据;}私人字符串 getPhoneNumber(int contactId) {String phoneNumber = "";final String[] 投影 = new String[] { Phone.NUMBER, Phone.TYPE, };final Cursor phone = managedQuery(Phone.CONTENT_URI,projection, Data.CONTACT_ID + "=?", new String[] { String.valueOf(contactId) }, null);如果(电话.moveToFirst()){final int contactNumberColumnIndex = phone.getColumnIndex(Phone.DATA);而 (!phone.isAfterLast()) {phoneNumber = phoneNumber + phone.getString(contactNumberColumnIndex) + ";";电话.moveToNext();}}电话.关闭();返回电话号码;}

如何使用?

ArrayList>contactList = getContacts();System.out.println("联系人列表:" +contactList);

输出:

[{电话 = 992-561-1618;848-807-4440;,联系人 ID=1,照片=android.graphics.Bitmap@44f40aa0,地址=Zalavadia StrretManavadar, 古吉拉特邦 362630印度,电子邮件= [email protected];[email protected];,名称=Biraj Zalavadia},{电话 = 992-511-1418;842-827-4450;,联系人 ID=2,照片=android.graphics.Bitmap@44f40aa0,地址=Makadiya Strret朱纳加德,古吉拉特邦 364890印度,[email protected];[email protected];,姓名=奈尔斯·帕特尔}......]

注意:

如果电话和电子邮件分号 (;) 超过一个,您将被分隔.

I am trying to get details of all the contacts available in phone contacts using below code. But facing small issue of duplicate values.

EDITED

ACTUAL CODE STARTS :-

private String refreshData() {
        String emaildata = "";
        try {
            ContentResolver cr = getBaseContext().getContentResolver();
            String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP
                    + " = '" + ("1") + "'";
            String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
                    + " COLLATE LOCALIZED ASC";
            Cursor cur = cr
                    .query(ContactsContract.Contacts.CONTENT_URI,
                            null,
                            selection
                                    + " AND "
                                    + ContactsContract.Contacts.HAS_PHONE_NUMBER
                                    + "=1", null, sortOrder);

            if (cur.getCount() > 0) {
                Log.i("Content provider", "Reading contact emails");
                while (cur.moveToNext()) {
                    mContactSet.add(cur.getString(cur
                            .getColumnIndex(ContactsContract.Contacts._ID)));
                }
            } else {
                emaildata += "Data not found.";
            }
            cur.close();

            Log.i(TAG, "Total contacts = " + mContactSet.size());
            Iterator<String> iterator = mContactSet.iterator();

            while (iterator.hasNext()) {
                String contactId = iterator.next();
                Log.i(TAG, "ID ==> " + contactId);

                // Create query to use CommonDataKinds classes to fetch
                // emails
                Cursor emails = cr.query(
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                        null, ContactsContract.CommonDataKinds.Email.CONTACT_ID
                                + " = " + contactId, null, null);

                // Name
                String whereName = ContactsContract.Data.MIMETYPE
                        + " = ? AND "
                        + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID
                        + " = ?";
                String[] whereNameParams = new String[] {
                        ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,
                        contactId };
                Cursor nameCur = cr
                        .query(ContactsContract.Data.CONTENT_URI,
                                null,
                                whereName,
                                whereNameParams,
                                ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
                while (nameCur.moveToNext()) {
                    String given = nameCur
                            .getString(nameCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
                    String family = nameCur
                            .getString(nameCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
                    String display = nameCur
                            .getString(nameCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));

                    Log.i(TAG, "First Name ==> " + given);
                    Log.i(TAG, "Last Name ==> " + family);
                    Log.i(TAG, "Display ==> " + display);
                }
                nameCur.close();

            }
        } catch (Exception e) {
            emaildata += "Exception : " + e + "";
        }
        return emaildata;
    }

Modified the query and get some better results but still the issue is same for some of the contacts and getting repeat values.

UPDATE :- I have used HashSet to get unique contact id and which I successfully get as well, but when I am getting the names from contact id I am getting the same value for 2-3 times for some of the contacts. I am very much confused that how this is possible that same contact is stored 2-3 times with same id?

DO I NEED TO USE HASHSET FOR FIRST NAME, LAST NAME, PHONE NUMBER, EMAIL, ETC? IS THERE ANY OTHER WAY?

解决方案

This is the complete solution

public ArrayList<HashMap<String, Object>> getContacts() {

        ArrayList<HashMap<String, Object>> contacts = new ArrayList<HashMap<String, Object>>();
        final String[] projection = new String[] { RawContacts.CONTACT_ID, RawContacts.DELETED };

        @SuppressWarnings("deprecation")
        final Cursor rawContacts = managedQuery(RawContacts.CONTENT_URI, projection, null, null, null);

        final int contactIdColumnIndex = rawContacts.getColumnIndex(RawContacts.CONTACT_ID);
        final int deletedColumnIndex = rawContacts.getColumnIndex(RawContacts.DELETED);

        if (rawContacts.moveToFirst()) {
            while (!rawContacts.isAfterLast()) {
                final int contactId = rawContacts.getInt(contactIdColumnIndex);
                final boolean deleted = (rawContacts.getInt(deletedColumnIndex) == 1);

                if (!deleted) {
                    HashMap<String, Object> contactInfo = new HashMap<String, Object>() {
                        {
                            put("contactId", "");
                            put("name", "");
                            put("email", "");
                            put("address", "");
                            put("photo", "");
                            put("phone", "");
                        }
                    };
                    contactInfo.put("contactId", "" + contactId);
                    contactInfo.put("name", getName(contactId));
                    contactInfo.put("email", getEmail(contactId));
                    contactInfo.put("photo", getPhoto(contactId) != null ? getPhoto(contactId) : "");
                    contactInfo.put("address", getAddress(contactId));
                    contactInfo.put("phone", getPhoneNumber(contactId));
                    contactInfo.put("isChecked", "false");
                    contacts.add(contactInfo);
                }
                rawContacts.moveToNext();
            }
        }

        rawContacts.close();

        return contacts;
    }

    private String getName(int contactId) {
        String name = "";
        final String[] projection = new String[] { Contacts.DISPLAY_NAME };

        final Cursor contact = managedQuery(Contacts.CONTENT_URI, projection, Contacts._ID + "=?", new String[] { String.valueOf(contactId) }, null);

        if (contact.moveToFirst()) {
            name = contact.getString(contact.getColumnIndex(Contacts.DISPLAY_NAME));
            contact.close();
        }
        contact.close();
        return name;

    }

    private String getEmail(int contactId) {
        String emailStr = "";
        final String[] projection = new String[] { Email.DATA, // use
                // Email.ADDRESS
                // for API-Level
                // 11+
                Email.TYPE };

        final Cursor email = managedQuery(Email.CONTENT_URI, projection, Data.CONTACT_ID + "=?", new String[] { String.valueOf(contactId) }, null);

        if (email.moveToFirst()) {
            final int contactEmailColumnIndex = email.getColumnIndex(Email.DATA);

            while (!email.isAfterLast()) {
                emailStr = emailStr + email.getString(contactEmailColumnIndex) + ";";
                email.moveToNext();
            }
        }
        email.close();
        return emailStr;

    }

    private Bitmap getPhoto(int contactId) {
        Bitmap photo = null;
        final String[] projection = new String[] { Contacts.PHOTO_ID };

        final Cursor contact = managedQuery(Contacts.CONTENT_URI, projection, Contacts._ID + "=?", new String[] { String.valueOf(contactId) }, null);

        if (contact.moveToFirst()) {
            final String photoId = contact.getString(contact.getColumnIndex(Contacts.PHOTO_ID));
            if (photoId != null) {
                photo = getBitmap(photoId);
            } else {
                photo = null;
            }
        }
        contact.close();

        return photo;
    }

    private Bitmap getBitmap(String photoId) {
        final Cursor photo = managedQuery(Data.CONTENT_URI, new String[] { Photo.PHOTO }, Data._ID + "=?", new String[] { photoId }, null);

        final Bitmap photoBitmap;
        if (photo.moveToFirst()) {
            byte[] photoBlob = photo.getBlob(photo.getColumnIndex(Photo.PHOTO));
            photoBitmap = BitmapFactory.decodeByteArray(photoBlob, 0, photoBlob.length);
        } else {
            photoBitmap = null;
        }
        photo.close();
        return photoBitmap;
    }

    private String getAddress(int contactId) {
        String postalData = "";
        String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
        String[] addrWhereParams = new String[] { String.valueOf(contactId), ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };

        Cursor addrCur = managedQuery(ContactsContract.Data.CONTENT_URI, null, addrWhere, addrWhereParams, null);

        if (addrCur.moveToFirst()) {
            postalData = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
        }
        addrCur.close();
        return postalData;
    }

    private String getPhoneNumber(int contactId) {

        String phoneNumber = "";
        final String[] projection = new String[] { Phone.NUMBER, Phone.TYPE, };
        final Cursor phone = managedQuery(Phone.CONTENT_URI, projection, Data.CONTACT_ID + "=?", new String[] { String.valueOf(contactId) }, null);

        if (phone.moveToFirst()) {
            final int contactNumberColumnIndex = phone.getColumnIndex(Phone.DATA);

            while (!phone.isAfterLast()) {
                phoneNumber = phoneNumber + phone.getString(contactNumberColumnIndex) + ";";
                phone.moveToNext();
            }

        }
        phone.close();
        return phoneNumber;
    }

How to use?

ArrayList<HashMap<String, Object>> contactList = getContacts();
        System.out.println("Contact List : " +contactList);

Output:

[
{
phone=992-561-1618;848-807-4440;,
contactId=1,
photo=android.graphics.Bitmap@44f40aa0,
address=Zalavadia Strret
Manavadar, Gujarat 362630
India,
[email protected];[email protected];,
name=Biraj Zalavadia
},
{
phone=992-511-1418;842-827-4450;,
contactId=2,
photo=android.graphics.Bitmap@44f40aa0,
address=Makadiya Strret
Junagadh, Gujarat 364890
India,
[email protected];[email protected];,
name=Niles patel
}
.......
]

NOTE:

You will get phone and email semicolon(;) separated if its more than one.

这篇关于如何在不重复的情况下获取所有联系人的名字、姓氏、电子邮件、电话号码等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 01:55