如何通过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,并希望通过其lookupkey获取此联系人。好吧,不行。 cursor.getCount()返回0。
有什么想法吗?
答案 0 :(得分: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,效果很好!