Anki-Android icon indicating copy to clipboard operation
Anki-Android copied to clipboard

Expand CardContentProvider to return card IDs and cardinfo details

Open joaquintoral opened this issue 10 months ago • 8 comments

Problem Statement

The current CardContentProvider only allows accessing cards through notes (notes/<note_id>/cards), which requires:

  1. Finding notes first
  2. Iterating through notes to discover cards
  3. No efficient way to search cards directly using Anki's query syntax

This limitation prevents:

  • Anki-Connect or other similar apps compatibility: Desktop Anki-Connect has findCards and cardsInfo actions that are currently not implemented on Android
  • Performance: For large collections (10,000+ cards), the note-first approach is inefficient
  • Card-based workflows: Many use cases need to work with cards directly (filtering by interval, deck, scheduling info, etc.)

Proposed Solution

Add two new ContentProvider endpoints:

  1. /cards - Search cards using Anki query syntax
  • Accepts Anki browser query syntax in selection parameter (e.g., "deck:MyDeck prop:ivl<20 -is:new")
  • Returns card IDs or full card data based on projection
  • Optimization: When only _id is requested, returns IDs without fetching full card objects (critical for large collections)
  1. /cards/<cardId> - Direct card access by ID

  2. Allows direct access to a card without knowing its note ID

  3. Returns full card information including scheduling data

  4. Expose scheduling fields

Add to FlashCardsContract.Card:

  • DUE - Card due date/time
  • INTERVAL - Card interval in days
  • EASE_FACTOR - Card ease factor
  • REVIEWS - Number of reviews

Code Example

// Search cards with Anki query syntax
val uri = FlashCardsContract.Card.CONTENT_URI
val cursor = contentResolver.query(
    uri,
    arrayOf(FlashCardsContract.Card._ID),  // Only request IDs for performance
    "deck:MyDeck prop:ivl<20 -is:new",    // Anki query syntax
    null,
    null
)

// Direct card access
val cardUri = Uri.withAppendedPath(FlashCardsContract.Card.CONTENT_URI, cardId.toString())
val cardCursor = contentResolver.query(
    cardUri,
    arrayOf(
        FlashCardsContract.Card._ID,
        FlashCardsContract.Card.NOTE_ID,
        FlashCardsContract.Card.DUE,
        FlashCardsContract.Card.INTERVAL,
        FlashCardsContract.Card.EASE_FACTOR,
        FlashCardsContract.Card.REVIEWS
    ),
    null, null, null
)
public object FlashCardsContract {

    public object Card {
        /**
         * The content:// style URI for cards. To access a specific card, append the card's ID
         * to this URI (e.g., content://authority/cards/12345).
         */
        @JvmField // required for Java API
        public val CONTENT_URI: Uri = Uri.withAppendedPath(AUTHORITY_URI, "cards")

        /**
         * This is the ID of the card itself (i.e. Card._ID).
         */
        @Suppress("ConstPropertyName", "ktlint:standard:backing-property-naming")
        public const val _ID: String = "_id"

        /**
         * The due date/time for the card (scheduling information)
         */
        public const val DUE: String = "due"

        /**
         * The interval in days for the card (scheduling information)
         */
        public const val INTERVAL: String = "interval"

        /**
         * The ease factor for the card (scheduling information)
         */
        public const val EASE_FACTOR: String = "ease_factor"

        /**
         * The number of reviews for the card (scheduling information)
         */
        public const val REVIEWS: String = "reviews"

        @JvmField // required for Java API
        public val DEFAULT_PROJECTION: Array<String> =
            arrayOf(
                _ID,
                NOTE_ID,
                CARD_ORD,
                CARD_NAME,
                DECK_ID,
                QUESTION,
                ANSWER,
            )

CardContentProvider changes

class CardContentProvider : ContentProvider() {
        private const val CARDS = 1100
        private const val CARDS_ID = 1101

init {
            fun addUri(
                path: String,
                code: Int,
            ) = sUriMatcher.addURI(FlashCardsContract.AUTHORITY, path, code)
            // Here you can see all the URIs at a glance
            addUri("notes", NOTES)
            addUri("notes_v2", NOTES_V2)
            addUri("notes/#", NOTES_ID)
            addUri("notes/#/cards", NOTES_ID_CARDS)
            addUri("notes/#/cards/#", NOTES_ID_CARDS_ORD)

            // These two
            addUri("cards", CARDS)
            addUri("cards/#", CARDS_ID)

            addUri("models", NOTE_TYPES)
            addUri("models/*", NOTE_TYPES_ID) // the note type ID can also be "current"
            addUri("models/*/empty_cards", NOTE_TYPES_ID_EMPTY_CARDS)
            addUri("models/*/templates", NOTE_TYPES_ID_TEMPLATES)
            addUri("models/*/templates/#", NOTE_TYPES_ID_TEMPLATES_ID)
            addUri("models/*/fields", NOTE_TYPES_ID_FIELDS)
            addUri("schedule/", SCHEDULE)
            addUri("decks/", DECKS)
            addUri("decks/#", DECKS_ID)
            addUri("selected_deck/", DECK_SELECTED)
            addUri("media", MEDIA)

            for (idx in sDefaultNoteProjectionDBAccess.indices) {
                if (sDefaultNoteProjectionDBAccess[idx] == FlashCardsContract.Note._ID) {
                    sDefaultNoteProjectionDBAccess[idx] = "id as _id"
                }
            }
        }

    @Suppress("RedundantNullableReturnType")
    override fun getType(uri: Uri): String? {
        // Find out what data the user is requesting
        return when (sUriMatcher.match(uri)) {
            NOTES_V2, NOTES -> FlashCardsContract.Note.CONTENT_TYPE
            NOTES_ID -> FlashCardsContract.Note.CONTENT_ITEM_TYPE

            // Added Cards and Cards_Id
            NOTES_ID_CARDS, NOTE_TYPES_ID_EMPTY_CARDS, CARDS -> FlashCardsContract.Card.CONTENT_TYPE
            NOTES_ID_CARDS_ORD, CARDS_ID -> FlashCardsContract.Card.CONTENT_ITEM_TYPE

            NOTE_TYPES -> FlashCardsContract.Model.CONTENT_TYPE
            NOTE_TYPES_ID -> FlashCardsContract.Model.CONTENT_ITEM_TYPE
            NOTE_TYPES_ID_TEMPLATES -> FlashCardsContract.CardTemplate.CONTENT_TYPE
            NOTE_TYPES_ID_TEMPLATES_ID -> FlashCardsContract.CardTemplate.CONTENT_ITEM_TYPE
            SCHEDULE -> FlashCardsContract.ReviewInfo.CONTENT_TYPE
            DECKS, DECK_SELECTED, DECKS_ID -> FlashCardsContract.Deck.CONTENT_TYPE
            else -> throw IllegalArgumentException("uri $uri is not supported")
        }
    }

// Under query

            CARDS -> {
                // Search for cards using the libanki browser syntax
                val columns = projection ?: FlashCardsContract.Card.DEFAULT_PROJECTION
                val query = selection ?: ""
                val cardIds = col.findCards(query)

                // Optimization: If only requesting _id (card ID), skip expensive card object fetching
                val onlyRequestingId = columns.size == 1 && columns[0] == FlashCardsContract.Card._ID

                if (onlyRequestingId) {
                    // Fast path: Just return card IDs without fetching full card objects
                    val rv = MatrixCursor(columns, cardIds.size)
                    for (cardId in cardIds) {
                        val rb = rv.newRow()
                        rb.add(cardId)
                    }
                    rv
                } else {
                    // Full path: Fetch full card data (for compatibility with existing code)
                    val rv = MatrixCursor(columns, cardIds.size)
                    for (cardId in cardIds) {
                        val card = col.getCard(cardId)
                        addCardToCursor(card, rv, col, columns)
                    }
                    rv
                }
            }
            CARDS_ID -> {
                // Direct access card with specific ID
                val cardId = uri.pathSegments[1].toLong()
                val columns = projection ?: FlashCardsContract.Card.DEFAULT_PROJECTION
                val rv = MatrixCursor(columns, 1)
                val card = col.getCard(cardId)
                addCardToCursor(card, rv, col, columns)
                rv
            }

    private fun addCardToCursor(
        currentCard: Card,
        rv: MatrixCursor,
        col: Collection,
        columns: Array<String>,
    ) {
        val cardName: String =
            try {
                currentCard.template(col).name
            } catch (je: JSONException) {
                throw IllegalArgumentException("Card is using an invalid template", je)
            }
        val question = currentCard.renderOutput(col).questionWithFixedSoundTags()
        val answer = currentCard.renderOutput(col).answerWithFixedSoundTags()
        val rb = rv.newRow()
        for (column in columns) {
            when (column) {
                FlashCardsContract.Card._ID -> rb.add(currentCard.id)
                FlashCardsContract.Card.NOTE_ID -> rb.add(currentCard.nid)
                FlashCardsContract.Card.CARD_ORD -> rb.add(currentCard.ord)
                FlashCardsContract.Card.CARD_NAME -> rb.add(cardName)
                FlashCardsContract.Card.DECK_ID -> rb.add(currentCard.did)
                FlashCardsContract.Card.QUESTION -> rb.add(question)
                FlashCardsContract.Card.ANSWER -> rb.add(answer)
                FlashCardsContract.Card.QUESTION_SIMPLE -> rb.add(currentCard.renderOutput(col).questionText)
                FlashCardsContract.Card.ANSWER_SIMPLE -> rb.add(currentCard.renderOutput(col, false).answerText)
                FlashCardsContract.Card.ANSWER_PURE -> rb.add(currentCard.pureAnswer(col))


                FlashCardsContract.Card.DUE -> rb.add(currentCard.due.toLong())
                FlashCardsContract.Card.INTERVAL -> rb.add(currentCard.ivl.toLong())
                FlashCardsContract.Card.EASE_FACTOR -> rb.add(currentCard.factor / 1000.0f)
                FlashCardsContract.Card.REVIEWS -> rb.add(currentCard.reps)


                else -> throw UnsupportedOperationException("Queue \"$column\" is unknown")
            }
        }
    }

joaquintoral avatar Jan 15 '26 11:01 joaquintoral

Hello! 👋 Thanks for logging this issue. Please remember we are all volunteers here, so some patience may be required before we can get to the issue. Also remember that the fastest way to get resolution on an issue is to propose a change directly, https://github.com/ankidroid/Anki-Android/wiki/Contributing

welcome[bot] avatar Jan 15 '26 11:01 welcome[bot]

Can I work on this?

Fandroid745 avatar Jan 15 '26 15:01 Fandroid745

No, this isn't a good first issue.

The API should be close to perfect first time, and needs heavy testing and discussion

david-allison avatar Jan 15 '26 16:01 david-allison

Should I take this? As it's related to ContentProvider which I already discussed with David

sanjaysargam avatar Jan 16 '26 06:01 sanjaysargam

Sounds great!

My only question at present is the "single ID" optimization: if multiple parameters are provided, should we still take the fast path?

I'd want to see this heavily tested, like the other endpoints

I'd also want to be sure we've made contact with a maintainer from AnkiConnect for Android, to be sure they're happy with the direction we're taking

david-allison avatar Jan 16 '26 07:01 david-allison

if multiple parameters are provided, should we still take the fast path?

No. We should take fast path ONLY when _id alone is requested

sanjaysargam avatar Jan 16 '26 08:01 sanjaysargam

@KamWithK Could you please check problem statement and proposed solution, direct card access (/cards and /cards/{id}) in the ContentProvider to improve performance and align with AnkiConnect’s findCards / cardsInfo APIs. Would love your quick thoughts on whether this matches your vision before I proceed with implementation

sanjaysargam avatar Jan 16 '26 08:01 sanjaysargam

Hello folks, as far as i've understood from this thread: INTERVAL, DUE and EASE fields didn't make it to the release 2.24. I am very curious if there are any plans to expose these (as well as other cards statistics) in the public api at some point though?


  • Moved to https://github.com/ankidroid/Anki-Android/issues/20458

david-allison avatar Mar 14 '26 00:03 david-allison