[英]Retrieve Contact Phone Number From URI in Android
在我从内置活动中检索他们的 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
“此数据所属的 Contacts 表中行的 ID。”
因为无论如何我都是从联系人表中获取 URI - 这不是必需的,并且应该替换以下内容。 ID 是与电话表中的联系人对应的 ID,而不是原始联系人。
ContactsContract.CommonDataKinds.Phone._ID
交换行在查询中返回了正确的结果。 目前一切似乎都运行良好。
这应该有效,(也许尝试丢失类型)
电话号码存储在自己的表中,需要单独查询。 要查询电话号码表,请使用存储在 SDK 变量 ContactsContract.CommonDataKinds.Phone.CONTENT_URI 中的 URI。 使用 WHERE 条件获取指定联系人的电话号码。
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
// Do something with phones
}
pCur.close();
}
对 Android 联系人 SQLite 数据库执行第二次查询。 根据存储在 ContactsContract.CommonDataKinds.Phone.CONTENT_URI 中的 URI 查询电话号码。 联系人 ID 作为 ContactsContract.CommonDataKinds.Phone.CONTACT_ID 存储在电话表中,WHERE 子句用于限制返回的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.