Search code examples
androidsqlitekotlinandroid-sqlite

Filter database and show results where 2 conditions are met


I'm trying to filter my sqlite database to show only results where more than one condition are met.

override fun onCreateLoader(p0: Int, p1: Bundle?): Loader<Cursor> {
    val projection = arrayOf(
            WalletEntry._ID,
            WalletEntry.KEY_TITLE,
            WalletEntry.KEY_LAST_DATE,
            WalletEntry.KEY_TRANSACTION_PLACE,
            WalletEntry.KEY_LAST_EXPENSE_VALUE,
            WalletEntry.KEY_LAST_TRANSACTION_TITLE,
            WalletEntry.KEY_VALUE_AFTER,
            WalletEntry.KEY_LOCALES,
            WalletEntry.KEY_CURRENCY
    )

    val data = "string" // specified result

    val selection = "${WalletEntry.KEY_TITLE} = ?" // AND WalletEntry.KEY_TRANSACTION_PLACE IS NOT NULL
    val selectionArgs = arrayOf(data)

    return applicationContext?.let { context ->
        CursorLoader(context,
                WalletEntry.CONTENT_URI,
                projection,
                selection,
                selectionArgs,
                null)
    }!!
}

What I mean, in provided code where I initialize selection I want to choose rows where title equals variable data and column KEY_TRANSACTION_PLACE is not null.

So, how should I correct my selection/selectionArgs to filter those results?


Solution

  • You almost had it:

    val selection = "${WalletEntry.KEY_TITLE} = ? AND ${WalletEntry.KEY_TRANSACTION_PLACE} IS NOT NULL"