我正在尝试检索联系人号码。我可以毫无问题地访问联系人姓名,但是当我尝试访问联系人号码时,我得到一个例外,因为getColumnIndex
返回-1,这意味着它无法找到我请求的列。但我无法理解为什么它从Android文档中找不到列时我看到该列确实存在。
这是我的代码:
public ArrayList<String> getContactById(String contactId)
{
Log.d("XYZ", "Contact id -> " + contactId);
ArrayList<String> contact = new ArrayList<String>();
ContentResolver cr = context.getContentResolver();
final String[] projection = new String[] {
Contacts.DISPLAY_NAME, // the name of the contact
Contacts.PHOTO_ID // the id of the column in the data table for the image
};
final Cursor curContact = cr.query(
Contacts.CONTENT_URI,
projection,
Contacts._ID + "=?", // filter entries on the basis of the contact id
new String[]{String.valueOf(contactId)}, // the parameter to which the contact id column is compared to
null);
if(curContact.moveToFirst()) {
final String name = curContact.getString(curContact.getColumnIndex(Contacts.DISPLAY_NAME));
final String photoId = curContact.getString(curContact.getColumnIndex(Contacts.PHOTO_ID));
Log.d("XYZ", "Name -> " + name);
Log.d("XYZ", "Photo id -> " + photoId);
}
// Get the phone numbers
final String[] phoneNumbersProjection = new String[] {
Phone.NUMBER,
Phone.TYPE,
};
final Cursor curPhone = cr.query(
Phone.CONTENT_URI,
projection,
Data.CONTACT_ID + " = " + contactId, null,
//new String[]{String.valueOf(contactId)},
null);
if(curPhone.moveToFirst()) {
final int contactNumberColumnIndex = curPhone.getColumnIndex(Phone.NUMBER);
final int contactTypeColumnIndex = curPhone.getColumnIndex(Phone.TYPE);
Log.d("XYZ", "contactNumberColumnIndex -> " + contactNumberColumnIndex);
Log.d("XYZ", "contactTypeColumnIndex -> " + contactTypeColumnIndex);
while(!curPhone.isAfterLast()) {
final String number = curPhone.getString(contactNumberColumnIndex);
final int type = curPhone.getInt(contactTypeColumnIndex);
final int typeLabelResource = Phone.getTypeLabelResource(type);
Log.d("XYZ", "Contact number -> " + number);
//Log.d("XYZ", "Number Type -> " + typeLabelResource);
//doSomethingWithAContactPhoneNumber(number, typeLabelResource);
curPhone.moveToNext();
}
}
curPhone.close();
curContact.close();
return contact;
}
使用:
Log.d("XYZ", "contactNumberColumnIndex -> " + contactNumberColumnIndex);
Log.d("XYZ", "contactTypeColumnIndex -> " + contactTypeColumnIndex);
我收到:
contactNumberColumnIndex -> -1
contactTypeColumnIndex -> -1
有人能弄明白我的代码有什么问题吗?
谢谢!
答案 0 :(得分:2)
您使用了错误的投影:
final String[] phoneNumbersProjection = new String[] {
Phone.NUMBER,
Phone.TYPE,
};
final Cursor curPhone = cr.query(
Phone.CONTENT_URI,
projection,
您应该使用phoneNumbersProjection
而不是之前用于其他查询的projection
。
通常,getColumnIndex()
会尝试从Cursor
中的列中查找列,因此如果找不到列,请首先检查您是否在查询中包含该列。< / p>
答案 1 :(得分:2)
final Cursor curPhone = cr.query(
Phone.CONTENT_URI,
phoneNumbersProjection,
Data.CONTACT_ID + " = " + contactId, null,
//new String[]{String.valueOf(contactId)},
null);