如何获取联系人的电子邮件ID

时间:2013-04-09 05:14:29

标签: android

我正在尝试获取A联系人的电子邮件地址。 我发现How to get contact email id?但我无法使用它。

我写了以下代码来获取电子邮件

             Cursor c1;
            c1 = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME);


            if(c1==null)
        return;
                    if(c1.getCount() > 0)
            {
                    while(c1.moveToNext())
                    {

                        String id = c1.getString(c1.getColumnIndex(Contacts._ID));
                                                    if(id==null)
                            continue;
                                                    Cursor email_crsr = getContentResolver().query(CommonDataKinds.Email.CONTENT_URI, null, CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
                        if(email_crsr!=null)
                              email = phone_crsr.getString(phone_crsr.getColumnIndex(CommonDataKinds.Email.DATA));

      }
    }

我正在关注异常: 04-09 10:38:59.487:E / AndroidRuntime(8150):引起:android.database.CursorIndexOutOfBoundsException:请求索引-1,大小为4

1 个答案:

答案 0 :(得分:1)

这可能会帮助你

    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(email);
                    }
                } 
                cur1.close();
            }
        }
        return names;
    }