5

I'm confused about whether to use MergeCursor or CursorJoiner.

I have a Cursor (A) with a load of data in it. Lets say there are 100 rows in Cursor (A) and 3 columns. What I want to do is insert (append) a new column to the Cursor so the resulting Cursor (B) has 100 rows but 4 columns.

At this moment in time I would like the 4th column to contain a default value for the 100 rows.

How would I do this?

4

1 回答 1

3

您可以在此处使用装饰器模式

为此,Android 有CursorWrapper,这是一个...

将所有调用委托给实际游标对象的 Cursor 包装类。此类的主要用途是扩展游标,同时仅覆盖其方法的子集。

假设您的新列被称为newColumn,并且它是类型,String那么您可以按照以下方式做一些事情:

class MyCursorWrapper extends CursorWrapper {
    private final String NEW_COLUMN = "newColumn";

    @Override
    public int getColumnCount() {
        // Count the virtual column in
        return getWrappedCursor().getColumnCount() + 1;
    }

    @Override
    public int getColumnIndex(String columnName) {
        // Return the virtual column if they are asking for it,
        // otherwise just use the original 
        if (columnName != null && columnName.equals("newColumn") {
            return getWrappedCursor().getColumnCount();
        }
        return mCursor.getColumnIndex(columnName);
    }

    public int getColumnIndexOrThrow(String columnName)
            throws IllegalArgumentException {
        // Same logic as getColumnIndex()
        if (columnName != null && columnName.equals(NEW_COLUMN) {
            return getWrappedCursor().getColumnCount();
        }
        return getWrappedCursor.getColumnIndexOrThrow(columnName);
    }

    @Override
    public String getColumnName(int columnIndex) {
         if (columnIndex == getWrappedCursor.getColumnCount()) {
             return NEW_COLUMN;
         }
         return getWrappedCursor().getColumnName(columnIndex);
    }

    @Override
    public String[] getColumnNames() {
        // Add our virtual column to the result from the original Cursor
        String original = getWrappedCursor().getColumnNames()
        String result = new String[original.length + 1];
        System.arrayCopy(original, 0, result, 0, original.length);
        result[original.length] = NEW_COLUMN;
        return result;
    }

    @Override
    public String getString(int columnIndex) {
        // For the last column, return whatever you need to return here
        // For real columns, just delegate to the original Cursor
        if (columnIndex == getWrappedCursor().getColumnCount()) {
            return yourResultHere();
        }
        return getWrappedCursor().getString(columnIndex);
    }
}
于 2019-07-11T22:31:27.970 回答