来自内容提供者的游标的自定义列名称

时间:2012-07-12 22:03:17

标签: android android-contentprovider

是否可以使用自定义列名而不是内容提供商提供的游标来获取游标?

我尝试以下

   private final String[] PROJ_CONTACT = {
                    ContactsContract.CommonDataKinds.Email.DISPLAY_NAME_PRIMARY + " AS " + Golfer.COLUMN_NAME,
                    ContactsContract.CommonDataKinds.Email.ADDRESS + " AS " + Golfer.COLUMN_EMAIL
            };

ContentResolver resolver = getActivity().getContentResolver();
Cursor cursor = resolver.query(
                    ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    PROJ_CONTACT,
                    SELECTION_BY_ID,
                    new String[] {Long.toString(id)},
                    null);

但我得到例外07-12 17:02:01.733: E/AndroidRuntime(7569): java.lang.IllegalArgumentException: Invalid column display_name AS name

1 个答案:

答案 0 :(得分:0)

可能的解决方案是创建一个游标包装器,它重新映射列名并使用它而不是内容提供者返回的游标,但是可能有更好的解决方案吗?

private class ContactCursor extends CursorWrapper {
    public ContactCursor(Cursor cursor) {
        super(cursor);
    }

    @Override
    public int getColumnIndex(String columnName) {
        if (Golfer.COLUMN_NAME.equalsIgnoreCase(columnName)){
            columnName = ContactsContract.CommonDataKinds.Email.DISPLAY_NAME_PRIMARY;
        }

        if (Golfer.COLUMN_EMAIL.equalsIgnoreCase(columnName)){
            columnName = ContactsContract.CommonDataKinds.Email.ADDRESS;
        }               

        return super.getColumnIndex(columnName);
    }
}