Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

android - How to get all contacts first name, last name, email, phone number, etc without duplicates

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...