我試圖檢索聯繫人的號碼。我可以毫無問題地訪問聯繫人名稱,但是當我嘗試訪問聯繫人號碼時,我得到一個異常,因爲getColumnIndex
返回-1,這意味着它無法找到我請求的列。但我不明白爲什麼它從Android文檔中找不到列,我發現該列確實存在。獲取與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
誰能弄清楚什麼是錯我的代碼?
謝謝!
剛剛添加,我正在學習本教程 - > http://www.app-solut.com/blog/2011/03/working-with-the-contactscontract-to-query-contacts- in-android/ – dazito