1
我試圖從具有API 23權限的聯繫人中獲取電話號碼,但電話號碼始終返回空字符串。獲取聯繫人的權限已被驗證,並且聯繫人顯示有效,但對於任何聯繫人而言,該電話號碼字段似乎不存在。 「cr.query ...」似乎沒有帶回任何東西,因爲「while(phones.moveToNext)」從不顯示爲真。 我正在使用下面的代碼來獲取電話號碼。任何想法爲什麼電話號碼不顯示任何聯繫人?Phone.NUMBER爲所有聯繫人返回空
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();
UPDATE: 不知道爲什麼這種方法是行不通的,但發現另一種確實可行的方法。
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();
}
此方法工作正常。
您可以編寫完整的代碼與日誌貓錯誤 – AndroidHacker
沒有錯誤,只是空洞的手機串。我編輯了上面的帖子,展示了一種可行的方法。測試的手機是Nexus 6P,以防有所作爲。 – user2431174