查询 phone 个号码

Query phone numbers

我正在学习如何开发 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 cusror 发出 move 指令,而是你正在发出移动(迭代) cursorContacts cursor.

而不是:-

            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
            }