2 annbnncnnd AnnBnnCnnD 于 2013.04.09 17:03 提问

从联系人中提取email异常

从一个联系人信息中提取Email

我用了下面的代码:

    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): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 4

2个回答

ce_la_vie
ce_la_vie   2013.04.09 17:41
已采纳

试试:

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;
    }
baimy1985
baimy1985   2013.04.09 21:54
phone_crsr 这个在哪初始化和赋值的,写错了吧,同时也没有移动cursor的动作。
Csdn user default icon
上传中...
上传图片
插入图片