[英]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.