查询电话号码

问题描述 投票:1回答:1

我正在学习如何开发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

有谁能够帮我?

android indexoutofboundsexception android-contacts
1个回答
2
投票

我相信你正试图访问错误的光标。

基本上,该消息表示您正在尝试从第一行(位置-1)之前的cursorPhone访问该行。这是因为没有向cursorPhone cusror发出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
            }
© www.soinside.com 2019 - 2024. All rights reserved.