You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决「Value must be ≥ 0但getColumnIndex返回-1」的Android查询错误?

解决Android获取联系人时「Value must be ≥ 0 but getColumnIndex can be -1」错误

错误原因

getColumnIndex()方法在Cursor中找不到目标列时会返回-1,而直接将-1传入getString()会触发非法参数异常,也就是你遇到的报错。
你当前代码调用query时传入null作为查询列参数(Projection),虽然理论上会返回所有列,但部分设备或系统版本可能不会返回你需要的特定列,或者存在列名兼容问题,导致getColumnIndex找不到目标列。

解决方案

1. 明确指定查询列

不要用null作为Projection,直接列出你需要的列名,既避免列缺失问题,还能优化查询性能。

2. 增加列存在性校验

在调用getString()之前,先判断getColumnIndex的返回值是否≥0,避免传入非法索引。

修改后的完整代码

private ArrayList<String> getAllPhoneContacts(){
    ArrayList<String> phoneList = new ArrayList<>();
    ContentResolver contentResolver = getContentResolver();

    // 明确指定需要查询的联系人列
    String[] contactProjection = {
        ContactsContract.Contacts._ID,
        ContactsContract.Contacts.HAS_PHONE_NUMBER
    };
    Cursor cursor = contentResolver.query(
        ContactsContract.Contacts.CONTENT_URI,
        contactProjection,
        null,
        null,
        null
    );

    if (cursor != null && cursor.getCount() > 0){
        while(cursor.moveToNext()){
            // 先获取列索引并校验
            int idIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            if (idIndex < 0) continue;
            String id = cursor.getString(idIndex);

            int hasPhoneIndex = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
            if (hasPhoneIndex < 0) continue;
            if (cursor.getInt(hasPhoneIndex) > 0){
                // 明确指定需要查询的手机号列
                String[] phoneProjection = {
                    ContactsContract.CommonDataKinds.Phone.NUMBER
                };
                Cursor phoneCursor = contentResolver.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    phoneProjection,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                    new String[]{id},
                    null
                );

                if (phoneCursor != null){
                    while(phoneCursor.moveToNext()){
                        int phoneNumIndex = phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                        if (phoneNumIndex >= 0){
                            String phoneNo = phoneCursor.getString(phoneNumIndex);
                            phoneList.add(phoneNo);
                        }
                    }
                    phoneCursor.close();
                }
            }
        }
        cursor.close();
    }
    return phoneList;
}

额外注意事项

  • 确保已在AndroidManifest.xml中添加联系人权限:
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    
  • Android 6.0及以上版本需要动态申请READ_CONTACTS权限,否则查询会返回空Cursor。

内容的提问来源于stack exchange,提问作者Black_Devil007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 10:40:46