Example usage for android.database MatrixCursor MatrixCursor

List of usage examples for android.database MatrixCursor MatrixCursor

Introduction

In this page you can find the example usage for android.database MatrixCursor MatrixCursor.

Prototype

public MatrixCursor(String[] columnNames, int initialCapacity) 

Source Link

Document

Constructs a new cursor with the given initial capacity.

Usage

From source file:net.sf.xfd.provider.PublicProvider.java

@Nullable
@Override/*from w  w w.j a v a2  s . c  om*/
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sortOrder) {
    String path = uri.getPath();

    if (TextUtils.isEmpty(uri.getPath())) {
        path = "/";
    }

    try {
        assertAbsolute(path);
    } catch (FileNotFoundException e) {
        return null;
    }

    path = canonString(path);

    if (!path.equals(uri.getPath())) {
        uri = uri.buildUpon().path(path).build();
    }

    if (!checkAccess(uri, "r")) {
        return null;
    }

    if (projection == null) {
        projection = COMMON_PROJECTION;
    }

    final OS os = base.getOS();
    if (os == null) {
        return null;
    }

    try {
        final MatrixCursor cursor = new MatrixCursor(projection, 1);

        final Object[] row = new Object[projection.length];

        final Stat stat = new Stat();
        final String name = extractName(path);
        final String mime = base.getTypeFast(path, name, stat);

        for (int i = 0; i < projection.length; ++i) {
            String col = projection[i];

            switch (col) {
            case BaseColumns._ID:
                row[i] = stat.st_ino;
                break;
            case COLUMN_DISPLAY_NAME:
                row[i] = name;
                break;
            case COLUMN_SIZE:
                row[i] = stat.st_size;
                break;
            case COLUMN_MIME_TYPE:
                row[i] = mime;
                break;
            default:
                row[i] = null;
            }
        }

        cursor.addRow(row);

        final Context context = getContext();
        assert context != null;

        final String packageName = context.getPackageName();

        cursor.setNotificationUri(context.getContentResolver(),
                DocumentsContract.buildDocumentUri(packageName + FileProvider.AUTHORITY_SUFFIX, path));

        return cursor;
    } catch (IOException e) {
        e.printStackTrace();

        return null;
    }
}

From source file:com.ichi2.anki.provider.CardContentProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    Timber.d("CardContentProvider.query");
    Collection col = CollectionHelper.getInstance().getCol(getContext());
    if (col == null) {
        return null;
    }//from w w  w. j  av a2 s .  co  m

    // Find out what data the user is requesting
    int match = sUriMatcher.match(uri);

    switch (match) {
    case NOTES: {
        /* Search for notes
         */
        // TODO: Allow sort order, then also update description in FlashCardContract
        String columnsStr = proj2str(projection);
        String query = (selection != null) ? selection : "";
        List<Long> noteIds = col.findNotes(query);
        if ((noteIds != null) && (!noteIds.isEmpty())) {
            String selectedIds = "id in " + Utils.ids2str(noteIds);
            Cursor cur;
            try {
                cur = col.getDb().getDatabase()
                        .rawQuery("select " + columnsStr + " from notes where " + selectedIds, null);
            } catch (SQLException e) {
                throw new IllegalArgumentException("Not possible to query for data for IDs " + selectedIds, e);
            }
            return cur;
        } else {
            return null;
        }
    }
    case NOTES_ID: {
        /* Direct access note
         */
        long noteId;
        noteId = Long.parseLong(uri.getPathSegments().get(1));
        String columnsStr = proj2str(projection);
        String selectedIds = "id = " + noteId;
        Cursor cur;
        try {
            cur = col.getDb().getDatabase()
                    .rawQuery("select " + columnsStr + " from notes where " + selectedIds, null);
        } catch (SQLException e) {
            throw new IllegalArgumentException("Not possible to query for data for ID \"" + noteId + "\"", e);
        }
        return cur;
    }

    case NOTES_ID_CARDS: {
        Note currentNote = getNoteFromUri(uri, col);
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Card.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        for (Card currentCard : currentNote.cards()) {
            addCardToCursor(currentCard, rv, col, columns);
        }
        return rv;
    }
    case NOTES_ID_CARDS_ORD: {
        Card currentCard = getCardFromUri(uri, col);
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Card.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        addCardToCursor(currentCard, rv, col, columns);
        return rv;
    }
    case MODELS: {
        HashMap<Long, JSONObject> models = col.getModels().getModels();
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Model.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        for (Long modelId : models.keySet()) {
            addModelToCursor(modelId, models, rv, columns);
        }
        return rv;
    }
    case MODELS_ID: {
        long modelId = getModelIdFromUri(uri, col);
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Model.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        HashMap<Long, JSONObject> models = col.getModels().getModels();
        addModelToCursor(modelId, models, rv, columns);
        return rv;
    }
    case MODELS_ID_TEMPLATES: {
        /* Direct access model templates
         */
        JSONObject currentModel = col.getModels().get(getModelIdFromUri(uri, col));
        String[] columns = ((projection != null) ? projection : CardTemplate.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        try {
            JSONArray templates = currentModel.getJSONArray("tmpls");
            for (int idx = 0; idx < templates.length(); idx++) {
                JSONObject template = templates.getJSONObject(idx);
                addTemplateToCursor(template, currentModel, idx + 1, rv, columns);
            }
        } catch (JSONException e) {
            throw new IllegalArgumentException("Model is malformed", e);
        }
        return rv;
    }
    case MODELS_ID_TEMPLATES_ID: {
        /* Direct access model template with specific ID
         */
        int ord = Integer.parseInt(uri.getLastPathSegment());
        JSONObject currentModel = col.getModels().get(getModelIdFromUri(uri, col));
        String[] columns = ((projection != null) ? projection : CardTemplate.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        try {
            JSONObject template = getTemplateFromUri(uri, col);
            addTemplateToCursor(template, currentModel, ord + 1, rv, columns);
        } catch (JSONException e) {
            throw new IllegalArgumentException("Model is malformed", e);
        }
        return rv;
    }

    case SCHEDULE: {
        String[] columns = ((projection != null) ? projection
                : FlashCardsContract.ReviewInfo.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        long selectedDeckBeforeQuery = col.getDecks().selected();
        long deckIdOfTemporarilySelectedDeck = -1;
        int limit = 1; //the number of scheduled cards to return
        int selectionArgIndex = 0;

        //parsing the selection arguments
        if (selection != null) {
            String[] args = selection.split(","); //split selection to get arguments like "limit=?"
            for (String arg : args) {
                String[] keyAndValue = arg.split("="); //split arguments into key ("limit") and value ("?")
                try {
                    //check if value is a placeholder ("?"), if so replace with the next value of selectionArgs
                    String value = keyAndValue[1].trim().equals("?") ? selectionArgs[selectionArgIndex++]
                            : keyAndValue[1];
                    if (keyAndValue[0].trim().equals("limit")) {
                        limit = Integer.valueOf(value);
                    } else if (keyAndValue[0].trim().equals("deckID")) {
                        deckIdOfTemporarilySelectedDeck = Long.valueOf(value);
                        if (!selectDeckWithCheck(col, deckIdOfTemporarilySelectedDeck)) {
                            return rv; //if the provided deckID is wrong, return empty cursor.
                        }
                    }
                } catch (NumberFormatException nfe) {
                    nfe.printStackTrace();
                }
            }
        }

        //retrieve the number of cards provided by the selection parameter "limit"
        col.getSched().reset();
        for (int k = 0; k < limit; k++) {
            Card currentCard = col.getSched().getCard();

            if (currentCard != null) {
                int buttonCount = col.getSched().answerButtons(currentCard);
                JSONArray buttonTexts = new JSONArray();
                for (int i = 0; i < buttonCount; i++) {
                    buttonTexts.put(col.getSched().nextIvlStr(getContext(), currentCard, i + 1));
                }
                addReviewInfoToCursor(currentCard, buttonTexts, buttonCount, rv, col, columns);
            } else {
                break;
            }
        }

        if (deckIdOfTemporarilySelectedDeck != -1) {//if the selected deck was changed
            //change the selected deck back to the one it was before the query
            col.getDecks().select(selectedDeckBeforeQuery);
        }
        return rv;
    }
    case DECKS: {
        List<Sched.DeckDueTreeNode> allDecks = col.getSched().deckDueList();
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Deck.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, allDecks.size());
        for (Sched.DeckDueTreeNode deck : allDecks) {
            long id = deck.did;
            String name = deck.names[0];

            addDeckToCursor(id, name, getDeckCountsFromDueTreeNode(deck), rv, col, columns);
        }
        return rv;
    }
    case DECKS_ID: {
        /* Direct access deck
         */
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Deck.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        List<Sched.DeckDueTreeNode> allDecks = col.getSched().deckDueList();
        long deckId;
        deckId = Long.parseLong(uri.getPathSegments().get(1));
        for (Sched.DeckDueTreeNode deck : allDecks) {
            if (deck.did == deckId) {
                addDeckToCursor(deckId, deck.names[0], getDeckCountsFromDueTreeNode(deck), rv, col, columns);
                return rv;
            }
        }

        return rv;
    }
    case DECK_SELECTED: {

        long id = col.getDecks().selected();
        String name = col.getDecks().name(id);
        String[] columns = ((projection != null) ? projection : FlashCardsContract.Deck.DEFAULT_PROJECTION);
        MatrixCursor rv = new MatrixCursor(columns, 1);
        JSONArray counts = new JSONArray(Arrays.asList(col.getSched().counts()));
        addDeckToCursor(id, name, counts, rv, col, columns);
        return rv;
    }
    default:
        // Unknown URI type
        throw new IllegalArgumentException("uri " + uri + " is not supported");
    }
}

From source file:cm.confide.ex.chips.RecipientAlternatesAdapter.java

/**
 * @return a new cursor based on the given cursor with all duplicate destinations removed.
 *
 * It's only intended to use for the alternate list, so...
 * - This method ignores all other fields and dedupe solely on the destination.  Normally,
 * if a cursor contains multiple contacts and they have the same destination, we'd still want
 * to show both./*from  w w  w .  j ava2 s. co  m*/
 * - This method creates a MatrixCursor, so all data will be kept in memory.  We wouldn't want
 * to do this if the original cursor is large, but it's okay here because the alternate list
 * won't be that big.
 */
// Visible for testing
/* package */ static Cursor removeDuplicateDestinations(Cursor original) {
    final MatrixCursor result = new MatrixCursor(original.getColumnNames(), original.getCount());
    final HashSet<String> destinationsSeen = new HashSet<String>();

    original.moveToPosition(-1);
    while (original.moveToNext()) {
        final String destination = original.getString(Query.DESTINATION);
        if (destinationsSeen.contains(destination)) {
            continue;
        }
        destinationsSeen.add(destination);

        result.addRow(new Object[] { original.getString(Query.NAME), original.getString(Query.DESTINATION),
                original.getInt(Query.DESTINATION_TYPE), original.getString(Query.DESTINATION_LABEL),
                original.getLong(Query.CONTACT_ID), original.getLong(Query.DATA_ID),
                original.getString(Query.PHOTO_THUMBNAIL_URI), original.getInt(Query.DISPLAY_NAME_SOURCE) });
    }

    return result;
}

From source file:com.mattprecious.telescope.FileProvider.java

/**
 * Use a content URI returned by/* ww w .  j  a  v a  2  s  .  c  o m*/
 * {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file
 * managed by the FileProvider.
 * FileProvider reports the column names defined in {@link android.provider.OpenableColumns}:
 * <ul>
 * <li>{@link android.provider.OpenableColumns#DISPLAY_NAME}</li>
 * <li>{@link android.provider.OpenableColumns#SIZE}</li>
 * </ul>
 * For more information, see
 * {@link ContentProvider#query(Uri, String[], String, String[], String)
 * ContentProvider.query()}.
 *
 * @param uri A content URI returned by {@link #getUriForFile}.
 * @param projection The list of columns to put into the {@link Cursor}. If null all columns are
 * included.
 * @param selection Selection criteria to apply. If null then all data that matches the content
 * URI is returned.
 * @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to
 * the <i>selection</i> parameter. The <i>query</i> method scans <i>selection</i> from left to
 * right and iterates through <i>selectionArgs</i>, replacing the current "?" character in
 * <i>selection</i> with the value at the current position in <i>selectionArgs</i>. The
 * values are bound to <i>selection</i> as {@link java.lang.String} values.
 * @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort
 * the resulting {@link Cursor}.
 * @return A {@link Cursor} containing the results of the query.
 */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    // ContentProvider has already checked granted permissions
    final File file = mStrategy.getFileForUri(uri);

    if (projection == null) {
        projection = COLUMNS;
    }

    String[] cols = new String[projection.length];
    Object[] values = new Object[projection.length];
    int i = 0;
    for (String col : projection) {
        if (OpenableColumns.DISPLAY_NAME.equals(col)) {
            cols[i] = OpenableColumns.DISPLAY_NAME;
            values[i++] = file.getName();
        } else if (OpenableColumns.SIZE.equals(col)) {
            cols[i] = OpenableColumns.SIZE;
            values[i++] = file.length();
        }
    }

    cols = copyOf(cols, i);
    values = copyOf(values, i);

    final MatrixCursor cursor = new MatrixCursor(cols, 1);
    cursor.addRow(values);
    return cursor;
}

From source file:com.hippo.content.FileProvider.java

/**
 * Use a content URI returned by/*from  w ww.j a  va  2  s.c o  m*/
 * {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file
 * managed by the FileProvider.
 * FileProvider reports the column names defined in {@link android.provider.MediaStore.MediaColumns}:
 * <ul>
 * <li>{@link android.provider.MediaStore.MediaColumns#DISPLAY_NAME}</li>
 * <li>{@link android.provider.MediaStore.MediaColumns#SIZE}</li>
 * <li>{@link android.provider.MediaStore.MediaColumns#DATA}</li>
 * </ul>
 * For more information, see
 * {@link ContentProvider#query(Uri, String[], String, String[], String)
 * ContentProvider.query()}.
 *
 * @param uri A content URI returned by {@link #getUriForFile}.
 * @param projection The list of columns to put into the {@link Cursor}. If null all columns are
 * included.
 * @param selection Selection criteria to apply. If null then all data that matches the content
 * URI is returned.
 * @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to
 * the <i>selection</i> parameter. The <i>query</i> method scans <i>selection</i> from left to
 * right and iterates through <i>selectionArgs</i>, replacing the current "?" character in
 * <i>selection</i> with the value at the current position in <i>selectionArgs</i>. The
 * values are bound to <i>selection</i> as {@link java.lang.String} values.
 * @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort
 * the resulting {@link Cursor}.
 * @return A {@link Cursor} containing the results of the query.
 *
 */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    // ContentProvider has already checked granted permissions
    final File file = mStrategy.getFileForUri(uri);

    if (projection == null) {
        projection = COLUMNS;
    }

    String[] cols = new String[projection.length];
    Object[] values = new Object[projection.length];
    int i = 0;
    for (String col : projection) {
        if (MediaStore.MediaColumns.DISPLAY_NAME.equals(col)) {
            cols[i] = MediaStore.MediaColumns.DISPLAY_NAME;
            values[i++] = file.getName();
        } else if (MediaStore.MediaColumns.SIZE.equals(col)) {
            cols[i] = MediaStore.MediaColumns.SIZE;
            values[i++] = file.length();
        } else if (MediaStore.MediaColumns.DATA.equals(col)) {
            cols[i] = MediaStore.MediaColumns.DATA;
            values[i++] = file.getPath();
        }
    }

    cols = copyOf(cols, i);
    values = copyOf(values, i);

    final MatrixCursor cursor = new MatrixCursor(cols, 1);
    cursor.addRow(values);
    return cursor;
}