如何
通过其id/lookupkey检索单个联系人和一些相关数据(例如电子邮件,电话号码,地址等)?
这是我用来添加联系人的代码(实际上是来自互联网,对我有用)。
// Asking the Contact provider to create a new contact
try {
result = this.context.getContentResolver().applyBatch(
ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this.context, "Exception: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
Uri myContactUri = result[0].uri;
int lastSlash = myContactUri.toString().lastIndexOf("/");
int length = myContactUri.toString().length();
int contactID = Integer.parseInt((String) myContactUri.toString()
.subSequence(lastSlash + 1, length));
return contactID;
现在我想获取这个新联系人。我该怎么做?我想出的只是这个:
ContentResolver content = context.getContentResolver();
String[] projection = { Data.LOOKUP_KEY, Data.MIMETYPE,
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Email.ADDRESS };
// Defines the selection clause
String selection = Data.LOOKUP_KEY + " = ?";
// Defines the sort order
String sortOrder = Data.LOOKUP_KEY;
String[] args = {"2400"};
Cursor cursor = content.query(Data.CONTENT_URI, projection, selection,
args, sortOrder);
当我删除选择时,我会得到所有联系人+他们的所有数据。所以我在我的案例中查找了密钥 2400,并希望通过其查找键获取此联系人。好吧,不起作用。cursor.getCount() 返回 0。
有什么想法吗?
我现在的解决方案是用于以下:
String[] projection = { Data.MIMETYPE,
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Email.ADDRESS };
// Defines the selection clause
String selection = ContactsContract.Data.RAW_CONTACT_ID + "=?";
// Defines the sort order
String sortOrder = Data.LOOKUP_KEY;
String[] args = { id+"" };
Cursor cursor = content.query(Data.CONTENT_URI, projection, selection,
args, sortOrder);
排序顺序无关紧要,但我使用RAW_CONTACT_ID,效果很好!