用户从他们的联系人中选择一个联系人,这是回调函数(我正在跳过onActivityResult(...)
代码,它工作正常):
private User addUserFromContactData(Intent data) {
Uri contactData = data.getData();
// Cursor loader to query contact information
CursorLoader cl = new CursorLoader(this);
String[] projection = { ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA };
cl.setProjection(projection);
cl.setUri(ContactsContract.CommonDataKinds.Email.CONTENT_URI);
cl.setSelection(ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?");
cl.setSelectionArgs(new String[] { contactData.getLastPathSegment() });
// Execute query and get results from cursor
Cursor c = cl.loadInBackground();
final int nameIndex = c.getColumnIndex(projection[0]);
final int emailIndex = c.getColumnIndex(projection[1]);
User user = null;
if (c.moveToFirst()) {
user = new User();
user.setName(c.getString(nameIndex));
user.setEmail(c.getString(emailIndex));
}
c.close();
return user;
}
此方法适用于具有电子邮件地址的联系人。但是当我选择没有它的联系人时,没有找到结果。电子邮件对我来说是可选的,所以如果没有电子邮件,我只会使用联系人姓名。好像我只选择带有电子邮件地址的联系人。
任何人都可以帮助我吗?也许我需要查询两次,第一次获取名称,第二次获得可选的电子邮件?
谢谢你们。
答案 0 :(得分:2)
解决。要做到这一点,需要两个查询(如果我只能用一个查询,请纠正我):
private User addUserFromContactData(Intent data) {
Uri contactData = data.getData();
// Cursor loader to query contact name
CursorLoader clName = new CursorLoader(this);
clName.setProjection(new String[] { ContactsContract.Contacts.DISPLAY_NAME });
clName.setUri(ContactsContract.Contacts.CONTENT_URI);
clName.setSelection(ContactsContract.Contacts._ID + " = ?");
clName.setSelectionArgs(new String[] { contactData.getLastPathSegment() });
// Cursor loader to query optional contact email
CursorLoader clEmail = new CursorLoader(this);
clEmail.setProjection(new String[] { ContactsContract.CommonDataKinds.Email.DATA });
clEmail.setUri(ContactsContract.CommonDataKinds.Email.CONTENT_URI);
clEmail.setSelection(ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?");
clEmail.setSelectionArgs(new String[] { contactData.getLastPathSegment() });
// Execute queries and get results from cursors
Cursor cName = clName.loadInBackground();
Cursor cEmail = clEmail.loadInBackground();
final int nameIndex = cName.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int emailIndex = cEmail.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
User user = null;
if (cName.moveToFirst()) {
user = new User();
user.setName(cName.getString(nameIndex));
}
// This only could be true if selected contact has at least one email
if (cEmail.moveToFirst() && user != null) {
user.setEmail(cEmail.getString(emailIndex));
}
cName.close();
cEmail.close();
return user;
}
感谢线索@Luksprog!在之前的代码中,我只是通过电子邮件查询联系人,因为CursorLoader
的{{1}}是Uri
。