我正在学习如何开发 Android 应用程序。但是我很难找回联系人的电话。
我能够使用以下代码列出所有联系人:
private static final String[] contactProjetion = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER
};
private void getContacts() {
Cursor cursorContacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, contactProjetion, null, null, ContactsContract.Contacts.DISPLAY_NAME);
while (cursorContacts.moveToNext()) {
String id = cursorContacts.getString(0);
String name = cursorContacts.getString(1);
String hasPhone = cursorContacts.getString(2);
}
}
但是当使用相同的逻辑搜索联系人的电话时:
String[] phoneProjetion = new String[]{
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, phoneProjetion, null, null, ContactsContract.CommonDataKinds.Phone.NUMBER);
while (cursorContacts.moveToNext()) {
String phone = cursorPhone.getString(1); // this line throw android.database.CursorIndexOutOfBoundsException
}
我有以下异常:
Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 2
谁能帮帮我?
最佳答案
我相信您正在尝试访问错误的光标。
基本上,消息是说您正在尝试从第一行(位置 -1)之前的 cursorPhone 访问行。这是因为没有向 cursorPhone 光标发出 move 指令,而是您正在发出移动(遍历)cursorContacts 光标。
代替:-
while (cursorContacts.moveToNext()) {
String phone = cursorPhone.getString(1); // this line throw android.database.CursorIndexOutOfBoundsException
}
我认为你应该使用:-
while (cursorPhone.moveToNext()) { //<<<< CHANGED
String phone = cursorPhone.getString(1); // this line throw android.database.CursorIndexOutOfBoundsException
}
关于android - 查询电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49071719/