我尝试在从内置活动中检索到联系人的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)传递给一个方法。该方法旨在通过给定类型(在本例中为ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)从ID返回电话号码。
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;
}
这个查询返回了电话号码的空值,也就是说它找不到我想要访问的行,说明我的查询出现了问题。但如果我检查一个有手机号码的联系人,怎么可能会出现0行的查询结果呢?
非常感谢您的帮助!
_ID
是针对数据库的,而CONTACT_ID
是用于在不查询特定表时的联系人 ID。这有帮助吗? - hwrdprkns