1

I'm using an SQLite database to store items. When I call items by their ids using where clause and selection args. If I pass a selection args array with more than one item id, it crashes with error:

Cannot bind argument at index 2 because the index is out of range. The statement has 1 parameters.

Here is how I perform the query:

    override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> { 
    loaderId = id 
    val selectionArgs = arrayOf("2", "1")
    return CursorLoader(activity!!,
            MenuContract.ItemEntry.CONTENT_URI,
            Constants.ITEM_PROJECTION_COLUMNS,           
            MenuContract.ItemEntry._ID + "=?",  
            selectionArgs,
            null
    ) 
}

It works fine if the selectionArgs array contains only one id. Not sure why.

1 Answer 1

1

The number of selection args must match the number of ?'s (placeholders). So the error is basically saying where do I put the second argument as I've already replaced the first ? (placeholder)

It works when there is only 1 array element, because there is only 1 ? (placeholder).

Perhaps you want :-

MenuContract.ItemEntry._ID + "=? OR " + MenuContract.ItemEntry._ID + "=?",

Then both arguments have a placeholder.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that worked! In my case the user can add items to favorites, and I'm storing the added items' ids in prefs so when the favorites screen opens, it fetches items based on those ids. Now, I guess, I need to form the selection string based on the number of items. This selection part is not intuitive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.