Francesco
Francesco

Reputation: 93

Android/SQLite - Bit operation on WHERE clause

I'd like to know if it's possible to do in Android something like this:

public Cursor getFlowsByCategory(int type, int categoryID, int limit) {

    SQLiteDatabase db = dbHelper.getReadableDatabase();

    final String[] columns = {ID, FLAGS, SUBJECT, AMOUNT, AMOUNT_NO, CATEGORY};
    final String selection = "((" + FLAGS + " & ?) >> 1 = ?) AND (" + CATEGORY + " = ?)";
    final String[] selectionArgs = {Integer.toString(Flow.FLOW_TYPE), Integer.toString(type), Integer.toString(categoryID)};

    return db.query(TABLE, columns, selection, selectionArgs, null, null, ID + " DESC", Integer.toString(limit));

}

FLAGS is a 1-byte bit mask and I'd like to select only the rows which has the second bit (position 1) of the mask on. The mask (Flow.FLOW_TYPE) is 0b00000010 and the type parameter can be either 0 or 1. It should work but it doesn't: what am I doing wrong?

Upvotes: 6

Views: 1806

Answers (1)

CL.
CL.

Reputation: 180010

The query function accepts only strings as parameters, but in SQLite, numbers and strings never compare equal (unless you have type affinity, but this works only for column values, not expressions).

You have to explicitly convert the parameters back to a number:

((...) >> 1 = CAST(? AS INTEGER)) AND ...

Upvotes: 6

Related Questions