【问题标题】:Query phone numbers查询电话号码
【发布时间】:2018-03-02 14:59:36
【问题描述】:

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

我相信您正在尝试访问错误的光标。

基本上,消息是说您正在尝试从 cursorPhone 访问第一行之前的行(位置 -1)。这是因为没有向 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
            }

【讨论】:

  • 这是一个 ctrl+c ctrl+v 问题:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多