從一個聯系人信息中提取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
試試:
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;
}