【发布时间】:2016-05-07 17:43:23
【问题描述】:
我正在尝试从具有 API 23 权限的联系人中获取电话号码,但电话号码始终返回一个空字符串。获取联系人的权限已经过验证,并且联系人显示为有效,但任何联系人的电话字段似乎都不存在。 “cr.query...”似乎没有带来任何回报,因为“while (phones.moveToNext)”永远不会显示为真。 我正在使用下面的代码来获取电话号码。任何想法为什么电话号码不显示任何联系人?
ContentResolver cr = getContentResolver();
cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor.moveToFirst()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
switch (type) {
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
// do something with the Home number here...
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
PhoneNumber = number;
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
// do something with the Work number here...
break;
}
}
phones.close();
}
cursor.close();
更新: 不知道为什么该方法不起作用,但找到了另一种有效的方法。
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[] { id }, null);
int phoneIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
if (cursor.moveToFirst()) {
PhoneNumber = cursor.getString(phoneIdx).toString();
}
这个方法很好用。
【问题讨论】:
-
你能用log cat error写你的完整代码吗
-
没有错误,只是空的电话字符串。我编辑了上面的帖子以显示一种有效的方法。测试的手机是 Nexus 6P,以防万一。