我的Android应用程序需要检索有关联系人的信息(即电话号码和姓名)。我使用getContentResolver().query()
编写了一些代码。在结果中,我看到正在返回该名称,以及其他信息,如当我上次联系那个人时,而不是电话号码。我做错了什么?
代码:
Log.w("MyApp", "requesting " + phonesUri.toString());
Cursor contactCursor = context.getContentResolver().query(person, null, null, null, null);
contactCursor.moveToFirst();
for (int i = 0; i < contactCursor.getColumnCount(); i ++) {
Log.w("MyApp", contactCursor.getColumnName(i) + ": " + contactCursor.getString(i));
}
输出:
W/MyApp (21477): requesting content://contacts/people/169/phones
W/MyApp (21477): times_contacted: 6
W/MyApp (21477): custom_ringtone: null
W/MyApp (21477): primary_organization: null
W/MyApp (21477): phonetic_name:
W/MyApp (21477): status: null
W/MyApp (21477): label: null
W/MyApp (21477): number: null
W/MyApp (21477): type: null
W/MyApp (21477): mode: null
W/MyApp (21477): last_time_contacted: 1278113641980
W/MyApp (21477): display_name: (name removed for privacy)
W/MyApp (21477): im_handle: null
W/MyApp (21477): _id: 169
W/MyApp (21477): number_key: null
W/MyApp (21477): starred: 0
W/MyApp (21477): primary_email: null
W/MyApp (21477): name: (name removed for privacy)
W/MyApp (21477): primary_phone: null
W/MyApp (21477): im_account: null
W/MyApp (21477): notes:
W/MyApp (21477): im_protocol: null
W/MyApp (21477): send_to_voicemail: 0
答案 0 :(得分:3)
您不需要编写自己的迭代方法来打印到屏幕/日志,在游标上调用DatabaseUtils.dumpCursorToString(cursor);
以获得原始输出的字符串表示。
电话号码存储在自己的表格中,需要单独查询。要查询电话号码表,请使用存储在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子句用于限制返回的数据。