如何在使用CursorLoader时仅获取具有电子邮件的联系人

时间:2015-05-04 06:02:20

标签: android android-contacts

我试图从拥有电子邮件地址的设备获取所有联系人。 现在我的代码(下面)获取所有联系人,我必须添加什么才能获得只有电子邮件的联系人?

final static String SELECTION = Contacts.DISPLAY_NAME_PRIMARY + "<>''" + " AND " + Contacts.IN_VISIBLE_GROUP + "=1";

final static String[] PROJECTION = {
            Contacts._ID, Contacts.LOOKUP_KEY, Contacts.DISPLAY_NAME_PRIMARY , Contacts.PHOTO_THUMBNAIL_URI, SORT_ORDER, Contacts.SORT_KEY_PRIMARY
        };    

  new CursorLoader(getActivity(),
          Contacts.CONTENT_URI,
          ContactsQuery.PROJECTION,
          ContactsQuery.SELECTION,
          null,
          Contacts.SORT_KEY_PRIMARY);

1 个答案:

答案 0 :(得分:-2)

试试这个

public ArrayList<String> getNameEmailDetails(){
        ArrayList<String> names = new ArrayList<String>();
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                Cursor cur1 = cr.query( 
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", 
                                new String[]{id}, null); 
                while (cur1.moveToNext()) { 
                    //to get the contact names
                    String name=cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    Log.e("Name :", name);
                    String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    Log.e("Email", email);
                    if(email!=null){
                        names.add(name);
                    }
                } 
                cur1.close();
            }
        }
        return names;
    }

一旦你从光标获得了所有联系人,你应该提供查询来获取电子邮件

Cursor cur1 = cr.query( 
                            ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", 
                                    new String[]{id}, null);

从cur1,您可以获得所有具有电子邮件ID的联系人。