在从内置 Activity 中检索到他们的 ID 号码后,我试图获取联系人的电话号码。但是,每当我在下面的代码中使用游标查询数据库时——即使我选择的联系人有一个手机号码,我也会返回零行。
谁能给我指明更好的方向或举例说明如何在获取用户 ID 后获取联系人的电话号码?
我的代码:
private Runnable getSMSRunnable() {
return new Runnable() {
public void run() {
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(i, CONTACTS_REQUEST_CODE);
}
};
}
返回日志输出
content://com.android.contacts/data/6802
我从中将 ID (6802) 传递给一个方法,该方法旨在从具有给定类型的 ID 返回电话号码(在本例中为 ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
public static String getContactPhoneNumberByPhoneType(Context context, long contactId, int type) {
String phoneNumber = null;
String[] whereArgs = new String[] { String.valueOf(contactId), String.valueOf(type) };
Log.d(TAG, String.valueOf(contactId));
Cursor cursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? and "
+ ContactsContract.CommonDataKinds.Phone.TYPE + " = ?", whereArgs, null);
int phoneNumberIndex = cursor
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
Log.d(TAG, String.valueOf(cursor.getCount()));
if (cursor != null) {
Log.v(TAG, "Cursor Not null");
try {
if (cursor.moveToNext()) {
Log.v(TAG, "Moved to first");
Log.v(TAG, "Cursor Moved to first and checking");
phoneNumber = cursor.getString(phoneNumberIndex);
}
} finally {
Log.v(TAG, "In finally");
cursor.close();
}
}
Log.v(TAG, "Returning phone number");
return phoneNumber;
}
对于电话号码返回 null -- 这意味着它找不到我试图访问的行 -- 这意味着我的查询有问题 -- 但是如果我检查一个有手机号码的联系人-- 我如何获得 0 行查询?
如有任何帮助,我们将不胜感激。非常感谢!
最佳答案
我找到了答案。
我没有从游标中获取任何行的原因是因为我正在使用该行
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
"The id of the row in the Contacts table that this data belongs to."
因为无论如何我都是从联系人表中获取 URI——这不是必需的,应该用以下内容代替。 ID 是电话表中联系人对应的 ID,而不是原始联系人。
ContactsContract.CommonDataKinds.Phone._ID
交换行在查询中返回了正确的结果。目前一切似乎都运作良好。
关于android - 在 Android 中从 URI 检索联系电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3370628/